Skip to main content
GameDev.net gamedev.net
🔒 Locked

const member function

Started by popsoftheyear Jun 2, 2009 at 12:49 PM 3 replies 1k views
Original Post
popsoftheyear
popsoftheyear
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????
rip-off
rip-off
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.
implicit
implicit
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.
Zahlman
Zahlman
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????


:)
iMalc
iMalc
Oh good, I'm not the only one who sometimes types "text" when meaning to type "test" [grin].

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.