Hello all. Ive been having a problem. I have a base class A and two derived classes B and C. I have a pointer to B, which I'll call E, that I want to store either A or C in, in the hopes of using just one storage location (E), as I want to store B OR C not both. It seems wasteful to have make storage for B and C when only one will be used. Also I want to be able to access data specific to these derived classes. So I've tried using a virtual function from the base which is overloaded by the derived classes to each return a pointer to themselves so I can access their data. So why does this below not work? Or even better, how can I make this work :D Thanks!
#include <iostream>
using std::cout;
class Base
{
public:
virtual Base* GetThis(){return this;}
};
class Derived: public Base
{
public:
virtual Derived* GetThis() {return this;}
void Test(){cout << "Test";}
};
int main()
{
Derived d;
Base *b = &d;
Derived *pD = b->GetThis();
return 0;
}
I get this:
error C2440: 'initializing' : cannot convert from 'Base *' to 'Derived *'
If you've read down to hear thank you for your patience! :D
It seems you've found a solution, but I might suggest a rethinking of your design. If you're going to need a B object, then make a B object. When you're finished and will need a C object, delete your B object and make your C object. That way you're not wasting any memory (which appears to have been your original reason for using inheritance) and you don't have to worry about these weird type casts.