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();
const member function
I have the following code:
From the compiler's perspective, why is TestFuncPointer a valid function, while TestFuncStack is not????
I am going to steal something NotAYakk wrote for a different thread:
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.
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.
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????
:)
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement