Newbie, instantiating a child class from its parent?

Hello, over the years of developing with C++ I still don't know if there is a better / more elegant way for doing the following simple program. The basic problem I face often is to instantiate a derived class from a parent class. Here is my code:

#include
#include
#include

using namespace std;

class CParent;
class CChild;
typedef auto_ptr PParent;
typedef auto_ptr PChild;

// Parent class interface
PChild Child_Create();
void Child_Test(PChild p);


class CParent
{
public:
CParent()
{
cout << "Hi, I'm a parent
";
if (m_ActiveInstances < 3)
{
m_ActiveInstances++;

//PChild c = CChild::Create(); (doesn't work, at least in devcpp)
PChild c = Child_Create(); // a bit strange, but works

//c->Test() // doesn't work
Child_Test(c); // somewhat odd, i'd prefer to use the above method..

}
}

~CParent()
{
cout << "Hi, a parent died
";
}

static int m_ActiveInstances;
};
int CParent::m_ActiveInstances = 0;

class CChild : public CParent
{
public:
CChild()
{
cout << "Hi, I'm a child
";
}

~CChild()
{
cout << "A child died
";
}

void Test()
{
cout << "The kid is crying!
";
}
static PChild Create();

};

// Is there a better way of calling a static function defined in a
// derived class, other than building those wrappers?
PChild Child_Create()
{
return (PChild)CChild::Create();
}

void Child_Test(PChild p)
{
p->Test();
}

PChild CChild::Create()
{
return (PChild)new CChild();
}


void test()
{
PParent m = (PParent)new CParent();
}

int main(int argc, char *argv[])
{
test();
system("PAUSE");
return EXIT_SUCCESS;
}

Hopefully, someone has done it before! Thankyou in advance.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories