using const causes compiler errors

I have the following class

1
2
3
4
5
6
7
8
class Test
{
public:
	void DoSomeStuff()
	{
		cout << "Doing some stuff ..." << endl;
	}
};


Using the class like follows, I do not get a compiler error. All works fine

1
2
Test test;
test.DoSomeStuff();


But if I write const before "Test test" like so

1
2
const Test test;
test.DoSomeStuff(); // Compiler Error! 

I get two error messages from the compiler:

error C2662: 'Test::DoSomeStuff' : cannot convert 'this' pointer from 'const Test' to 'Test &'


IntelliSense: the object has type qualifiers that are not compatible with the member function


Why it doesn't work with const?
You can only call the member functions that are marked with const on const objects.
Change line 4 to void DoSomeStuff() const. Now inside this function you will not be able to change member variables or call other non-const member functions.
An instantiation of an object that's declared constant can only invoke constant methods of the same class. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Test
{
    public:
        void DoSomeStuff() // Not constant
        {
            std::cout << "Test::DoSomeStuff()" << std::endl;
        }

        void DoSomeStuff() const // Constant
        {
            std::cout << "Test::DoSomeStuff() const" << std::endl;
        }
};

int main()
{
    const Test NewTest;
    NewTest.DoSomeStuff();
}

Here, the first definition of Test::DoSomeStuff() isn't constant because no const follows the function header. However, the second definition of Test::DoSomeStuff() is constant because const follows the function header.

It's quite simple: If const follows the function header, the function is considered read-only; that is, the function cannot alter any members of the class, regardless. A read-only function can only appear in a class.

Note this:
You can only invoke read-only methods from constant instantiations of the same class.

Compile the above code and see what happens.

Wazzak
Last edited on
Thanks!!
Topic archived. No new replies allowed.