-1

How do I get the output of this code segment to print "Function of Child Class"?

I'm having trouble understanding why writing

BaseClass obj = DerivedClass();

causes a similar output

#include <iostream>
using namespace std;
class BaseClass {
public:
   void disp(){
      cout<<"Function of Parent Class";
   }
   void dispOther(BaseClass& other) {
       other.disp();
   }
};
class DerivedClass: public BaseClass{
public:
   void disp() {
      cout<<"Function of Child Class";
   }
};

BaseClass getInstance() {
   BaseClass obj = DerivedClass();
   return obj;
}

int main() {
   auto obj = getInstance();
   auto obj2 = DerivedClass();
   obj2.dispOther(obj);
   return 0;
}

output:

Function of Parent Class 

1 Answers1

2

Object Slicing. obj is a base class, even if it's being assigned from a derived class object.

To override functions in a derived class you need yo make the disp() function virtual, then try this:

DerivedClass d;
BaseClass& obj = d;

obj.disp();
Chad
  • 18,706
  • 4
  • 46
  • 63
  • Thank you! So taking d as a reference prevents losing the info then? – person123456 Jun 16 '18 at 21:37
  • 1
    References (or pointers) to base classes can refer (or point) to derived objects. – Chad Jun 16 '18 at 21:38
  • You also need to make the `disp()` function virtual. – Chad Jun 16 '18 at 21:43
  • Given all your other provisos and edits, this would be the same as `d.disp();` I'm not sure how this answers the question. –  Jun 16 '18 at 21:59
  • The OPs leading question is "why does `BaseClass obj = DerivedClass ()` give the output he sees. The two reasons are lack of `virtual` and object slicing. Aside from rewriting all if the OPs code in this answer, I'm honestly not sure what else I could provide. – Chad Jun 17 '18 at 01:39