#include<iostream>
#include<math.h>

class real
{
  double value;
  double error;
public:
  real(const double,const double);
  double get_value();
  double get_error();
  friend bool operator<=(const real&,const double);
};

real::real(const double val, const double err) : value(val), error(fabs(err)) {}

double real::get_value()
{
  return value;
}

double real::get_error()
{
  return error;
}

bool operator<=(const real& x1, const double x2)
{
  return x1.get_value() + x1.get_error() < x2;
}

int main()
{
  return 0;
}

Compiler error:
passing 'const real' as 'this' argument of 'double real::get_alue()' discards qualifiers

However since operator <= is a friend x1.value or x1.error is valid!

Recommended Answers

All 3 Replies

Didn't we already go over this with you? If you want to call a member function through a const object, the member function should be qualified as const too:

#include<iostream>
#include<math.h>

class real
{
  double value;
  double error;
public:
  real(const double,const double);
  double get_value() const;
  double get_error() const;
  friend bool operator<=(const real&,const double);
};

real::real(const double val, const double err) : value(val), error(fabs(err)) {}

double real::get_value() const
{
  return value;
}

double real::get_error() const
{
  return error;
}

bool operator<=(const real& x1, const double x2)
{
  return x1.get_value() + x1.get_error() < x2;
}

int main()
{
  return 0;
}

In fact, any member functions that don't modify the state of the object should be qualified as const.

And the syntax is always

double get_value() const;

or can be

const double get_value() const;

?

I also have to write const after the operator<= ? like this:

bool operator<=(const real& x1, const double x2) const

>And the syntax is always
>double get_value() const;

Yes.

>or can be
>const double get_value() const;

That's different. The leading const is applied to the return type and means you want to return a const double. The trailing const is applied to the member function and means the member function doesn't modify an object's state.

>I also have to write const after the operator<= ?
No, because that's illegal. const can only be applied to member functions.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.