Sign in to follow this  
popsoftheyear

const member function

Recommended Posts

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????

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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????


:)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this