class Base
{
public:
int nX;
int nY;
Base(){};
~Base(){};
};
class Derived
{
private:
Base pBase;
int mX;
int mY;
public:
Derived(){}
Derived(int x , int y) { pBase.nX = x; pBase.nY = y;}
~Derived(){}
void Print()
{
std::cout<<"Base X is "<< pBase.nX << ", Base Y is " << pBase.nY << std::endl;
}
};
int main()
{
Derived pDerived(10,9);
Base* pBase = reinterpret_cast<Base*>(&pDerived);
pDerived.Print();
std::cout<<"Cast X is "<< pBase->nX<<", Cast Y is "<< pBase->nY<<std::endl;
return 0;
}
I have come across something above in a Source which did not inherit a Base Class, yet Include it as part of the class/struct, sent to another consumer function as a base pointer, then using reinterpret_cast
to cast it back to the Derived class(or another) Depending on the value of nX
.
nX
is Guaranteed to be unique for every class, At least from what I can see from the source.
I've oversimplified it's usage for the code, and I'm Calling it as Base
and Derived
due to the lack of a better term since I have absolutely no idea what to call this practice.
The code does seem to grab the proper address, and does output the correct values for nX
and nY
, and the Applications logic does work as well. The classes doesn't have any virtual
functions except for a Default Constructor, unlike my example. I have also kept the structure
of the class in my sample, with the member variables above the constructors/member Functions.
My question is, How are objects Stored in memory either automatically or dynamically, Are guaranteed to behave this way(Stored Similar to Structs as stated on an answer on this thread, given the Code above.)? or is this an undefined behavior, and not fixing this would eventually run into segmentation faults or Access Violations?