I`ve faced with a very interesting issue, i hope you can help me what i am doing wrong here..
class abstract1
{
public:
virtual ~ abstract1(){};
virtual void funk1()=0;
virtual void punk1()=0;
};
class abstract2
{
public:
virtual ~ abstract2(){};
virtual void funk2()=0;
virtual void punk2()=0;
};
class Derived: public abstract1,
public abstract2
{
public:
Derived(){ cout<<"Derived constructor"<<endl;};
~Derived() {cout <<"Derived destructor" <<endl;};
void funk1(){
cout<<"funk1 function in Derived!!!"<<endl;
};
void punk1(){
cout<<"punk1 in Derived!!!"<<endl;
};
void funk2(){
cout<<"funk2 function in Derived!!!"<<endl;
};
void punk2(){
cout<<"punk2 in Derived!!!"<<endl;
};
};
class myapi{
public:
void start(void *_drved){
drved=(abstract2*)_drved;
};
void callback(){
drved->funk2();
drved->punk2();
}
protected:
abstract2* drs;
};
Here I have defined two base classes and one derived class inheriting from these two. main() implementation is as follows:
int main() {
Derived* myderived =new Derived();
myapi* dbmodule= new myapi();
dbmodule->start(myderived);
dbmodule->callback();
return 0
}
I expect to see that funk2 and punk2 are getting called one after another. However result is shockingly new to me . Callback() seems to call funk1 and punk1. Screen output is like below:
Derived constructor
funk1 function in Derived!!!
punk1 in Derived!!!
Hope you can let me know what i am getting wrong here.Thanks
(abstract2*)on a void pointer ends up inreinterpret_castinstead ofdynamic_cast.std::cout << reinterpret_cast<abstract2*>(myderived)andstd::cout << static_cast<abstract2*>(myderived)void*useDerived*or, since you're ultimately using a pointer to anabstract2, start with a pointer to that, which will let you use any class that derives from that without the type-unsafety of avoid*. Substituting void* with Derived* produces the behavior you expectedvoid *in C++, it often doesn't do what you want it to. In this case the simple solution is to use templates for thestartfunction.