This “base” class constructs for b , medium1 and medium2. When i use “top” class, it construct 2 times more. Totally constructing 5 times(writing to screen 5 times).
Question: What can i change in the “base” class to make it construct only once and for all.?
#include "stdafx.h"
#include<stdlib.h>
class base
{
public:
base(){x=5;printf(" %i ",x);}
int x;
}b;
class medium1:public base{}m1;
class medium2:public base{}m2;
class top:public medium1,medium2{};
int main() {
top ten;
getchar();
return 0;
}
what are pitfalls of virtual base class? Thanks for answering my trivial question.
It is not possible to have
baseconstruct only once instead of all five original constructions. You have four complete objects in your program that containbasesubobjects. This immediately means that regardless of what you do, you will have at least fourbaseconstructions.Additionally, the suggestion to use virtual inheritance mentioned in other answers will actually require making changes to other classes, not to
baseclass. Meanwhile your question insists that changes shall be made tobase.