Interview Question
- 0of 0 votes
Answer#include <cstdlib> #include <iostream> using namespace std; class Empty {}; class Derived1 : public Empty {}; class Derived2 : virtual public Empty {}; class Derived3 : public Empty { char c; }; class Derived4 : virtual public Empty { char c; }; class Dummy { char c; }; int main(int argc, char *argv[]) { cout << "sizeof(Empty) " << sizeof(Empty) << endl; cout << "sizeof(Derived1) " << sizeof(Derived1) << endl; cout << "sizeof(Derived2) " << sizeof(Derived2) << endl; cout << "sizeof(Derived3) " << sizeof(Derived3) << endl; cout << "sizeof(Derived4) " << sizeof(Derived4) << endl; cout << "sizeof(Dummy) " << sizeof(Dummy) << endl; system("PAUSE"); return EXIT_SUCCESS; }
and the out put is (In Dev c++)
- Learn Android: http://learnandroideasily.blogspot.in/ April 27, 2012 in India
sizeof(Empty) 1
sizeof(Derived1) 1
sizeof(Derived2) 4
sizeof(Derived3) 1
sizeof(Derived4) 8
sizeof(Dummy) 1
why the size of derived2 is 4 and the size of derived 4 is 8.| Report Duplicate | Flag | PURGE
As derived2 is virtually inheritating Empty class. It will get _vptr as a hidden pointer. and pointer is having size of 4 byte(32 bit machine)
- amit priyadarshi April 30, 2012derived4 is virtually inheritating Empty class. It will also get _vptr as a hidden pointer (4 byte)
and it is haivng char c as its data member , so total size will be 4 + 1 = 5, but on 4 byte word memory m/c ,
1st 4 byte is for pointer _vptr
5th byte is for char and remaing 3 byte will be padded. so total size = 8 byte