2

Why must the base class object be a reference to call the derived virtual function ?

   #include<iostream>
    using namespace std;

    class A {

    public:
        virtual void print() { cout << "Hello 1" << endl; }

    };

    class B : public A {

    public:
        int x;
        void print() { cout << "Hello " << x << endl; }

    };

    void main(){

        B obj1;
        A &obj2 = obj1;
        A obj3 = obj1; // Why it is different from obj2

        obj1.x = 2;

        obj1.print();
        obj2.print();
        obj3.print(); // ?

    }
Charles Salvia
  • 52,325
  • 13
  • 128
  • 140
faressoft
  • 19,053
  • 44
  • 104
  • 146

2 Answers2

5

When you assign a derived object to a base variable, it gets "sliced" into an instance of the base class; it's no longer an instance of the derived one. That's necessary because the base variable only has enough space reserved for an instance of the base class; an instance of a derived class, with its additional data, won't fit.

When you use a reference, the object doesn't have to be copied into a smaller space, so slicing doesn't occur.

Wyzard
  • 33,849
  • 3
  • 67
  • 87
3
A obj3 = obj1; // Why it is different from obj2

Constructs obj3 by copying. In this case obj1 is upcast to an A type where obj3 in constructed from obj1's "A" parameters. This phenomena is known as slicing.

A &obj2 = obj1;

This line binds the reference obj2 to an instance of obj1. You've upcasted obj1 to an "A" by pointing obj2 to it. Keep in mind in C++ a reference is really just an alias. You've just given obj1 a different name where that name is bound to a base class type.

So A obj3 allocates and constructs a brand new object on the stack while A &obj2 just creates a reference/alias for some other thing that already exists.

Community
  • 1
  • 1
Doug T.
  • 64,223
  • 27
  • 138
  • 202