mans
mans

Reputation: 18228

const parameter and const method in c++

I have a class like this:

class MyClass
{
    const int GetValue()
    {   
        return 2;
     }
}

and I am passing it to a function like this:

void Test(const MyClass &myClass)
{
   int x=myClass.GetValue();
}

But I am getting this error:

The object has type qualifiers that are not compatible with member function Object type is const MyClass

I know that if I define function like this:

void Test( MyClass &myClass)

But I want to know why adding const should generate such error?

Upvotes: 2

Views: 198

Answers (3)

Marco A.
Marco A.

Reputation: 43662

There are two problems, a visibility problem (your const int GetValue() function is not visible since private) and the fact that you're calling a non-const function (which can perform modifications to the object which has it as a member function)

const int GetValue()

from a constant reference to the class

const MyClass &myClass

you are basically asking for "This object shall not be modified, anyway let me call a function which does not guarantee this".

You're not being coherent.

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227578

You need to make the member function const, not the return type:

int GetValue() const;

This makes it possible to call this member on a const instance (or via a const reference or pointer).

Note: as you are returning by value, the constness of the thing you return is decoupled from the constness of the object returning it. In fact, it is very unlikely that you want the return type to be const.

Upvotes: 8

AlexanderBrevig
AlexanderBrevig

Reputation: 1987

You set the int to const, try making the method const like so:

const int GetValue() const
{   
    return 2;
}

Upvotes: 1

Related Questions