Aescleal is right, that's a fair description of what's wrong with the implementation.
I guess you would like to see how it could be made to work though.
#include "conio.h"
#include "iostream"
using namespace std;
class CBase
{
public:
int m_nBaseData;
virtual ~CBase() {}
virtual void Display() = 0;
};
class CDerived :
public CBase
{
public:
int m_nDerivedData;
void Display()
{
cout<<"CDerived::Display() : "<<m_nBaseData<<endl;
}
};
void main()
{
CBase* ptr[2] = {new CDerived(),new CDerived()};
CBase* ptr1 = ptr[0];
CBase* ptr2 = ptr[1];
ptr1->m_nBaseData = 10;
ptr2->m_nBaseData = 20;
ptr1->Display();
ptr2->Display();
getch();
delete ptr1;
delete ptr2;
}
ptr is an array of two pointers to CBase allocated on the stack - no need to delete it.
The instances are allocated dynamically, so deleting them before we exit is good practice.
I guess you wanted to be able to call the
Display()
function on both instances through your CBase pointers, well this does the trick. It could also be coded like this:
ptr[0]->Display();
ptr[1]->Display();
So your inital code wasn't that far off, and Aescleal gave you a well reasoned explaination on what was wrong with it.
I also added a virtual destructor
virtual ~CBase() {}
to CBase.
I feel that this is a good practice when developing class hierarchies, since it allows you to implement cleanup logic in derived classes that will be executed during destruction, even if delete is called on a pointer to a parent class.
Regards
Espen Harlinn