Question #269162

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.


Expert's answer

#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;

}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS