Answer to Question #269167 in C++ for kool

Question #269167

Q1: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.

a) Write a program such that base class pointer or reference will always access/call the base version

of the members available in derived class, do not have any access to the derived class members.

b) Write a program such that base class pointer or reference will always access/call the derived

version of the members available in derived class, do not have any access to the base class

members.


1
Expert's answer
2021-11-20T06:39:05-0500

a)

#include <iostream>
using namespace std;
class ABC{
    public:
    void display(){
        cout<<"class ABC\n";
    }
};
class BBC: public ABC{
    public:
    void display(){
        cout<<"class BBC\n";
    }
};
class KBC: public ABC{
    public:
    void display(){
        cout<<"Class KBC\n";
    }
};
int main(){
    ABC *ptr;
    KBC kbc;
    BBC bbc;


    ptr = &kbc;
    ptr->display();
    
    ptr = &bbc;
    ptr->display();
    
    return 0;
}

b)

#include <iostream>
using namespace std;
class ABC{
    public:
    virtual void display(){
        cout<<"class ABC\n";
    }
};
class BBC: public ABC{
    public:
    void display(){
        cout<<"class BBC\n";
    }
};
class KBC: public ABC{
    public:
    void display(){
        cout<<"Class KBC\n";
    }
};
int main(){
    ABC *ptr;
    KBC kbc;
    BBC bbc;


    ptr = &kbc;
    ptr->display();
    
    ptr = &bbc;
    ptr->display();


    return 0;
}

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