const member function

Started by
3 comments, last by iMalc 14 years, 10 months ago
I have the following code:
struct A {
	bool changed;
};

struct B {
	A *pObj;
	A sObj;
	B() : pObj(new A) { }
	void TestFuncPointer() const {
		pObj->changed = true;
	}
	void TestFuncStack() const {
		sObj.changed = true;
	}
};

B test;
test.TestFuncPointer();
test.TextFuncStack();

From the compiler's perspective, why is TestFuncPointer a valid function, while TestFuncStack is not????
Advertisement
I am going to steal something NotAYakk wrote for a different thread:
Quote:
foo* -- a pointer to a non-const foo
foo const* -- a pointer to a const foo
foo* const -- a const pointer to a non-const foo
foo const* const -- a const pointer to a const foo

With a const member function, it marks sObj as const (which we understand) and pObj like the third one above. That is, we cannot point pObj at another instance, but we can modify *pObj.

Finally, "stack" isn't the opposite of pointer. "Value" is. Remember, members are stored where the object is allocated, if the object is on the stack then its members are, if the object is on the heap again so are its members. The function should be called TestFuncValue.
Or imagine an iObj member storing an index into a global object array rather than an explicit pointer, along with a constant TestFuncIndexed function to set it.
This is situation is analogous.
Quote:Original post by popsoftheyear
I have the following code:
// ...B test;test.TestFuncPointer();test.TextFuncStack();//     ^ <-- !


From the compiler's perspective, why is TestFuncPointer a valid function, while TestFuncStack is not????


:)
Oh good, I'm not the only one who sometimes types "text" when meaning to type "test" [grin].
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

This topic is closed to new replies.

Advertisement