I know that as far as good programming practices go this is a bad idea, but I've been trying to solve a relatively difficult problem and was hoping for some insight. Essentially I'm trying to output all members of a class as follows:
class protoCalc
{
private:
int x;
int y;
virtual int basicAddition()
{
return x + y;
}
virtual int basicMultiplication()
{
return x*y;
}
public:
protoCalc(){
x = 14;
y = 120;
}
};
Accessing x and y proved easy enough; to do so I wrote a function (included my thoughts as to how this works, whether they're correct or not):
int private_member_Print(void* proto)
{
protoCalc* medium = (protoCalc*)proto;
protoCalc halfway = *medium;
int* ptr = ((int *)(&halfway));
return ptr[1];
}
The above will return the value of x, if ptr[2] is used it will return the value of y.
Now I have two questions, the first being what is ptr[0] pointing to? Shouldn't that bit of memory be occupied by the private member x seeing as that's the first member of class protoCalc? If not, then what does occupy this address?
Secondly, how do I access the virtual functions? My first intuition was that address ptr[3] would be occupied by the basicAddition() virtual function and ptr[4] the basicMultiplication() function, however this is not the case. When this failed to be true my next thought was that ptr[0] contained the pointer to the location of the virtual member table that held the two functions I was seeking. However, this also proved to be false.
So how do I access these virtual functions outside of the class as I have accessed the private members x and y? Obviously I could change the circumstances to make it easier, but that would defeat the purpose of the problem.