R
RK
I recently compiled and ran a program where I called a global function from
within a private function (which is ok) with the address of a private class
member variable (which is not ok?).
e.g.
#include <iostream>
void myFunc(int *intptr){*intptr = 99;}
class myClass
{
public:
myClass() : myData(0){};
void myClassPublicFunc(){myClassProtectedFunc();}
void printData(){std::cout << myData << std::endl;};
private:
void myClassProtectedFunc(){myFunc(&myData);}
int myData;
};
int main()
{
myClass myClassInstance;
myClassInstance.myClassPublicFunc();
myClassInstance.printData();
return 0;
}
I was quite surprised that this actually works since it seems to defy the
member access rules of C++. How is it that I can give out to a global
function the address of a private member variable? Aren't pointers to member
variables simply an offset from the start of the object's address and not an
actual address? I looked up my copy of ISO 14882 to solve this mystery with
no luck...
If it matters, I use a compiler from a large software company in Seattle.
Thanks
within a private function (which is ok) with the address of a private class
member variable (which is not ok?).
e.g.
#include <iostream>
void myFunc(int *intptr){*intptr = 99;}
class myClass
{
public:
myClass() : myData(0){};
void myClassPublicFunc(){myClassProtectedFunc();}
void printData(){std::cout << myData << std::endl;};
private:
void myClassProtectedFunc(){myFunc(&myData);}
int myData;
};
int main()
{
myClass myClassInstance;
myClassInstance.myClassPublicFunc();
myClassInstance.printData();
return 0;
}
I was quite surprised that this actually works since it seems to defy the
member access rules of C++. How is it that I can give out to a global
function the address of a private member variable? Aren't pointers to member
variables simply an offset from the start of the object's address and not an
actual address? I looked up my copy of ISO 14882 to solve this mystery with
no luck...
If it matters, I use a compiler from a large software company in Seattle.
Thanks