Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 773
Sumanth V Avatar asked Oct 31 '22 00:10

Sumanth V


1 Answers

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....

like image 116
2 revs Avatar answered Nov 15 '22 04:11

2 revs