Forked from prehistoricpenguin/virtual_inheritance_difference.cpp
Last active
July 18, 2017 06:45
-
-
Save theidexisted/9d0f1ebda9f2c56ad49c6623833d191b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <cctype> | |
#include <fstream> | |
#include <iostream> | |
#include <iterator> | |
#include <set> | |
#include <string> | |
using namespace std; | |
class Furniture { | |
public: | |
Furniture() { | |
_price = 0; | |
std::cout << __FUNCTION__ << " ctor" << std::endl; | |
} | |
virtual ~Furniture() { cout << "Furiture dtor" << endl; } | |
virtual int Price() { return _price; } | |
protected: | |
int _price; | |
}; | |
class Sofa : virtual public Furniture { | |
public: | |
Sofa() : _color(2) { | |
_price = 1; | |
std::cout << __FUNCTION__ << " ctor" << std::endl; | |
} | |
virtual ~Sofa() { cout << "sofa dtor" << endl; } | |
virtual int Color() { return _color; } | |
virtual void SitDown() { cout << "Sofa sitdown" << endl; } | |
protected: | |
int _color; | |
}; | |
class Bed : virtual public Furniture { | |
public: | |
Bed() : _length(4), _width(5) { | |
_price = 3; | |
std::cout << __FUNCTION__ << " ctor" << std::endl; | |
} | |
virtual ~Bed() { cout << "Bed dtor" << endl; } | |
virtual int Area() { return _length * _width; } | |
virtual void Sleep() { cout << "Bed sleep" << endl; } | |
protected: | |
int _length; | |
int _width; | |
}; | |
class SofaBed : public Sofa, public Bed { | |
public: | |
SofaBed() : _height(6) { std::cout << __FUNCTION__ << " ctor" << std::endl; } | |
virtual ~SofaBed() { cout << "SofaBed dtor" << endl; } | |
virtual void SitDown() { cout << "SofaBed sitdown" << endl; } | |
virtual void Sleep() { cout << "SofaBed sleep" << endl; } | |
virtual int Height() { return _height; } | |
protected: | |
int _height; | |
}; | |
int main() { | |
SofaBed sbed; | |
cout << sizeof(Furniture) << endl; | |
cout << sizeof(Sofa) << endl; | |
cout << sizeof(Bed) << endl; | |
cout << sizeof(sbed) << endl; | |
return 0; | |
} | |
/* | |
output from gcc 5.4 x86_64: | |
Furniture ctor | |
Sofa ctor | |
Bed ctor | |
SofaBed ctor | |
16 | |
32 | |
32 | |
56 | |
SofaBed dtor | |
Bed dtor | |
sofa dtor | |
Furiture dtor | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Object ABI:
From the memory layout, we can see that the underlay object model is:
_vptr.Sofa
_color.Sofa
_vptr.Bed
_length.Bed
_width.Bed
_height.SofaBed
_vptr.Furniture
_price.Furniture