Naresh
Naresh

Reputation: 155

Number of vptr created if derived class also has a virtual function which is not present in Base class

class Base
{
    public:
    
    virtual void func1()
    {
        std::cout<<"Base func1"<<std::endl;
    }
   //virtual destructor

};

class Derived : public Base
{
    public:
    
    virtual void func1()
    {
        std::cout<<"Derived Base func1"<<std::endl;
    }
    
    virtual void func2()
    {
        std::cout<<"Derived func2"<<std::endl;
    }
};


int main()
{
    Derived *d = new Derived;
    delete d;
}

I want to know if there will be two "vptr"s created for resolving virtual functions, one in the Base class which will be inherited in Derived class object for func1 and other one in the Derived object for func2.

Upvotes: 0

Views: 661

Answers (2)

Red.Wave
Red.Wave

Reputation: 4251

vtable/vptr issues are platform specific implementation details, not generally covered by std. I can imagine implementations with no in-object vptr at all. But on most platforms I know, exactly one vptr entry serves all purposes for single inheritance and virtual inheritance. However there is no warranty for this to be portable behavior.

Upvotes: 0

HolyBlackCat
HolyBlackCat

Reputation: 96568

On my GCC:

std::cout << sizeof(void*) << ' ' << sizeof(Derived) << '\n';
// Prints 8 8

So one vtable pointer is enough. I'd expect most other compilers to behave in the same way.

derived class also has a virtual function which is not present in Base class

Virtual functions added in Derived are probably simply placed at the end of Derived vtable, after functions inherited from Base.

Upvotes: 1

Related Questions