Sumanth V
Sumanth V

Reputation: 71

Virtual functions using base and derived objects

I have read about vtable and have understood the concept for base class pointers pointing to base and derived class objects. Can someone explain the case how vtable is created when both base class and derived class are objects and derived class object is assigned to base class object. Case 3 in the below example

#include <iostream>
#include <exception>
using namespace std;


class Base
{
public:
    virtual void function1() { cout<<"Base - func1"<<endl; }
    virtual void function2() { cout<<"Base - func2"<<endl; }
};

class Derived1: public Base
{
public:
    virtual void function1() { cout<<"Derived1 - func1"<<endl; }
};

class Derived2: public Base
{
public:
    virtual void function2() { cout<<"Derived2 - func2"<<endl; }
};

int main () 
{
    // Case 1
    Base* B1 = new Derived1();
    B1->function1();
    B1->function2();

    // Case 2
    cout<<endl;
    Base* B2 = new Derived2();
    B2->function1();
    B2->function2(); 

    // Case 3
    cout<<endl;
    Base B3;
    Derived1 D1;
    B3=D1;
    B3.function1();
    B3.function2(); 
}

output:

Derived1 - func1
Base - func2

Base - func1
Derived2 - func2

Base - func1
Base - func2

Upvotes: 5

Views: 180

Answers (2)

Piotr Siupa
Piotr Siupa

Reputation: 4838

Base B3;
D1 Derived;
B3=Derived;  //There is called default assignment operator

It is defined like that:

Base& operator=(const Base &objectToCopy) {...}

The operator takes an argument of type Base, so object of type D1 is treated as object of type Base. It means the assignment operator see only that fields of Derived which are in class Base. However, pointer to vtable (which technically is a hidden field) still is not copied, because it always create in constructor and it is permanently associated with the real object type.

Upvotes: 0

Tony Delroy
Tony Delroy

Reputation: 106096

B3=Derived; is an example of object slicing... only the base class data members are assigned to, and the vtable pointer continues to point to the base class functions.

You should avoid slicing - it can be dangerous (see this answer for an explanation). Now you know the term, you'll easily find plenty of reading on object slicing....

Upvotes: 2

Related Questions