I have two classes B and D
class B{
public:
virtual int prva()=0;
virtual int druga(int)=0;
};
class D: public B{
public:
virtual int prva(){return 42;}
virtual int druga(int x){return prva()+x;}
};
My task is to create a function that takes pointer to object B nad prints returning values of methods 'prva' and 'druga' without using their name (accessing through virtual table)
I wrote the following code that successfully prints the returning value of method 'prva', but then fails to do the same for the second method 'druga'
typedef int (*PTRFUN1)(void);
typedef int (*PTRFUN2)(int);
void function (B* var){
int* vptr = *(int**)var;
PTRFUN1 fun1 = (PTRFUN1)vptr[0];
PTRFUN2 fun2 = (PTRFUN2)vptr[1];
pprintf("Prva:%d\n", fun1());
printf("Druga:%d\n", fun2(2));
}
int main(void){
B *pb = new D();
function(pb);
}
This code executes printing: "Prva:42"
It fails to call prva()
inside of 'druga' and I can't figure out why.
Additionally, if I simply remove call of prva()
and let the body just be return x
, the method 'druga' will always return "42" or whatever number i let 'prva' return no matter what argument I try to send through fun2()
Any ides what am I doing wrong here, and how should I access methods?