1

I have following C++ code.

#include<iostream>
using namespace std;

class A
{
    int aa;
    public:

    virtual void sound()
    {
        cout << "I am A" << endl;   
    }
};

class B:public A
{
    int bb;
    public:

    void sound()
    {
        cout << "I am B" <<endl;    
    }
};

class C:public B
{
    int cc;
    public:

    void sound()
    {
        cout << "I am C"<<endl; 
    }
};

int main()
{
    A* a = new A();
    B* b = new B();
    C* c = new C();
    cout << "size of A :" << sizeof(A) << endl;
    cout << "size of B :" << sizeof(B) << endl;
    cout << "size of C :" << sizeof(C) << endl; 
}

This code produces the following output.

size of A :16 size of B :16 size of C :24

And without the virtual keyword in sound method in class A it produces.

size of A :4 size of B :8 size of C :12

So, that means for v-tables some memory has been allocated and it is not equal among the 3 classes. I am unable to figure it out how much of memory is allocated per class when there are virtual functions and when there are no virtual functions. Can someone please explain me above 2 scenarios.

update 1: compiler version : gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1) OS : ubuntu 14.04

update 2: given possible duplicate explains about padding in structs. When applied the same concept here, question regarding virtual functions is solved. But when we remove the virtual keyword it seems the private variable of the parent class has come into the child class. Can someone explain this?

sampath
  • 53
  • 1
  • 7
  • Your vtable is adding 8 bytes. As for why the total size differs between those classes, see [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](http://stackoverflow.com/questions/119123) – Drew Dormann Feb 13 '15 at 03:36

0 Answers0