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
foo
objectconst
, but the object pointed byfoo.mybar
is notconst
. You never made itconst
. So, why do you expect the const method to be called for*foo.mybar
? Basically, when you are illustrating an obvious and straightforward behavior and ask a "why" question there's no way to even begin answering this question, since there's no way to even begin to understand how and why someone would ask it. – Schmitt1
is equal to1
. How does one answer such a question? There's just no way to answer it because there's really no question here. – Schmittmybar2
is a part offoo
. When you makefoo
const, you automatically makemybar2
const.*mybar1
is not a part offoo
, so it doesn't become const. – Schmittusing namespace std
, that's an abomination and I'm against using it in even the simplest sample code, because novices are learning it from there. – Corporateusing
debate would not have been half as convincing had you not given such a good counterargument to mine. – Corporate