C++ Inheritance

Write output with explanation.

class Base
{
public:
     virtualvoid fun()
     {
          cout<<"fun of base"<<endl;
     }
     void run()
     {
          fun();
     }
};
class Derived : public Base
{
public:
     void fun()
     {
          cout<<"fun of derived"<<endl;
     }
};
void main()
{
     Derived d;
     d.run();
}

Output: fun of derived

Description:

The main use of virtual function is that it supports the runtime polymorphism. You can call the derived class function by using base class object. This is not the scenario of the given program. Object of class derived simply call the fun() function, so output will be:
fun of derived.

Write output with explanation.

class P
{
public:
     void print()
     {
          cout<<"inside P!!"<<endl;
     }
};
class Q : public P
{
public:
     void print()
     {
          cout<<"inside Q!!"<<endl;
     }
};
class R : public Q
{

};
void main ( )
{
     R r;
     r.print();
}

Output: Inside Q!!

Description:
  • The above program shows the concept of multilevel inheritance. In main function object of class 'R' is created. class 'R' is empty class, there is no print function is written in this class but it inherited the public member of its base class.
  • In multilevel inheritance, if the target function is not available, it searches the function in base class and executed that function, if available.