Answer to Question #269162 in C++ for kool

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.


1
Expert's answer
2021-11-20T09:49:28-0500
#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!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS