Define a class ABC. Derive two classes BBC and KBC from ABC. All the classes contains same member function name as display(). The base class pointer always holds the derived class objects.
#include <iostream>
using namespace std;
class ABC
{
public:
ABC(int id=0) : id(id) {}
void display() {
cout << "ABC: " << id << endl;
}
protected:
int id;
};
class BBC : public ABC
{
public:
BBC(int id=0) : ABC(id) {}
void display() {
cout << "BBC: " << id << endl;
}
};
class KBC : private ABC
{
public:
KBC(int id=0) : ABC(id) {}
void display() {
cout << "KBC: " << id << endl;
}
};
int main()
{
ABC *p = new ABC(1);
cout << "Pointer to ABC:" << endl << endl;
p->display();
delete p;
p = new BBC(2);
cout << "Pointer to BBC:" << endl << endl;
p->display();
delete p;
p = reinterpret_cast<ABC*>(new KBC(3));
cout << "Pointer to KBC:" << endl << endl;
p->display();
delete p;
}
Comments
Leave a comment