Reputation: 1911
I have the following scenario. There are two Base classes: Base1, Base2 and two derived classes: Derived, sysCommandExecutor which are derived as follows:
#include <iostream>
using namespace std;
class Base1 { virtual void dummy() {} };
class Base2 { virtual void dumy() {} };
class Derived: virtual public Base1, public Base2
{ int a; };
class sysCommandExecutor : public Base2
{
public:
int b;
Base1 *ptr;
void func(void);
};
void sysCommandExecutor::func(void)
{
Derived *d;
d = dynamic_cast<Derived *>(ptr);
if (d == NULL)
std::cout << "This is NULL" << std::endl;
else
{
// Call a function of Derived class
}
}
int main () {
try {
sysCommandExecutor * sys = new sysCommandExecutor;
sys->func();
return 0;
}
}
I want to call this function of "Derived" class inside func but the dynamic_cast fails. I cannot create the function in the sysCommandExecutor class as that is someone else's code. How to make the ptr pointer in sysCommandExecutor class to point to Derived class object??
Thanks in advance
Upvotes: 0
Views: 357
Reputation: 849
You are referencing an uninitialized pointer ptr
if i change main to:
int main () {
sysCommandExecutor * sys = new sysCommandExecutor;
sys->ptr=new Derived;
sys->func();
delete dynamic_cast<Derived *>(sys->ptr);
delete sys;
return 0;
}
it works
you are missing a virtual dtor as well
Upvotes: 1