C++ | Inheritance | Question 10

Output of following program?

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
#include<string>
using namespace std;
  
class Base
{
public:
    virtual string print() const
    {
        return "This is Base class";
    }
};
  
class Derived : public Base
{
public:
    virtual string print() const
    {
        return "This is Derived class";
    }
};
  
void describe(Base p)
{
    cout << p.print() << endl;
}
  
int main()
{
    Base b;
    Derived d;
    describe(b);
    describe(d);
    return 0;
}

chevron_right


(A)

This is Derived class
This is Base class

(B)

This is Base class
This is Derived class

(C)

This is Base class
This is Base class

(D) Compiler Error


Answer: (C)

Explanation: Note that an object of Derived is passed in describe(d), but print of Base is called. The describe function accepts a parameter of Base type.

This is a typical example of object slicing, when we assign an object of derived class to an object of base type, the derived class object is sliced off and all the data members inherited from base class are copied. Object slicing should be ovoided as there may be surprising results like above. As a side note, object slicing is not possible in Java. In Java, every non-primitive variable is actually a reference.

Quiz of this Question

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Article Tags :
Practice Tags :


1


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