I know this has been asked a lot, but the only answers I could find was when the const-ness was actually casted away using (int*) or similar. Why isn't the const qualifier working on pointer type member variables on const objects when no cast is involved?
#include <iostream>
class bar {
public:
void doit() { std::cout << " bar::doit() non-const\n"; }
void doit() const { std::cout << " bar::doit() const\n"; }
};
class foo {
bar* mybar1;
bar mybar2;
public:
foo() : mybar1(new bar) {}
void doit() const {
std::cout << "foo::doit() const\n";
std::cout << " calling mybar1->doit()\n";
mybar1->doit(); // This calls bar::doit() instead of bar::doit() const
std::cout << " calling mybar2.doit()\n";
mybar2.doit(); // This calls bar::doit() const correctly
}
// ... (proper copying elided for brevity)
};
int main(void)
{
const foo foobar; // NOTE: foobar is const
foobar.doit();
}
The code above yields the following output (tested in gcc 4.5.2 and vc100):
foo::doit() const calling mybar1->doit() bar::doit() non-const <-- Why ? calling mybar2.doit() bar::doit() const
I am going to answer my own question in this case. Fred Nurk's answer is correct but does not really explain the "why".
mybar1
and*mybar1
are different. The first refer to the actual pointer and the latter the object. The pointer is const (as mandated by the const-ness on foo; you can't domybar1 = 0
), but not the pointed to object, as that would require me to declare itconst bar* mybar1
. The declarationbar* mybar1
is equivalent tobar* const mybar1
when the foo object is const (i.e. pointer is const, not pointed to object).C++ by default gives a so called bitwise constness - meaning it ensures that no single bit of object has been changed, so it just checks the address of the pointer.
You can read more about it in great book "Effective c++" by S. Meyers
When a foo instance is const, its data members are const too, but this applies differently for pointers than you might at first think:
The type of obj.p is int * const, not int const *; that is, a constant pointer to int, not a pointer to constant int.
For another way to look at it, let's start with a function:
Now imagine we have an A instance, and we make it const. You can imagine that as applying const_ on each data member.
The variable be_wary_of_where_you_place_const shows that "adding const" is not the same as prepending "const" to the literal text of a type.