Output of C++ Program | Set 3

Predict the output of below C++ programs.

Question 1

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream>
  
using namespace std;
class P {
public:
   void print()
   { cout <<" Inside P::"; }
};
  
class Q : public P {
public:
   void print()
   { cout <<" Inside Q"; }
};
  
class R: public Q {
};
  
int main(void)
{
  R r;
  
  r.print();
  return 0;
}

chevron_right


Output:
Inside Q

The print function is not defined in class R. So it is looked up in the inheritance hierarchy. print() is present in both classes P and Q, which of them should be called? The idea is, if there is multilevel inheritance, then function is linearly searched up in the inheritance heirarchy until a matching function is found.


Question 2



filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream>
#include<stdio.h>
  
using namespace std;
  
class Base
{
public:
  Base()
  {
    fun(); //note: fun() is virtual
  }
  virtual void fun()
  {
    cout<<"\nBase Function";
  }
};
  
class Derived: public Base
{
public:
  Derived(){}
  virtual void fun()
  {
    cout<<"\nDerived Function";
  }
};
  
int main()
{
  Base* pBase = new Derived();
  delete pBase;
  return 0;
}

chevron_right


Output:
Base Function

See following excerpt from C++ standard for explanation.

When a virtual function is called directly or indirectly from a constructor (including from the mem-initializer for a data member) or from a destructor, and the object to which the call applies is the object under construction or destruction, the function called is the one defined in the constructor or destructor’s own class or in one of its bases, but not a function overriding it in a class derived from the constructor or destructor’s class, or overriding it in one of the other base classes of the most derived object.

Because of this difference in behavior, it is recommended that object’s virtual function is not invoked while it is being constructed or destroyed. See this for more details.

Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above.



My Personal Notes arrow_drop_up


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.