-2

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.

huseyin tugrul buyukisik
  • 11,469
  • 4
  • 45
  • 97

5 Answers5

6

It is not possible to have base construct only once instead of all five original constructions. You have four complete objects in your program that contain base subobjects. This immediately means that regardless of what you do, you will have at least four base constructions.

Additionally, the suggestion to use virtual inheritance mentioned in other answers will actually require making changes to other classes, not to base class. Meanwhile your question insists that changes shall be made to base.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
5

This will construct base only once when you create a top class.

class medium1:virtual public base{};
class medium2:virtual public base{};

The rest come from the fact that you create objects b, m1 and m2. You can't really prevent calling the destructor of the base class because, well, that's what you tell the compiler to do. If you don't want to create base objects, don't derive from it.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
2

You can make it a virtual base class, but that comes with a giant set of pitfalls.

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806
1

You can have a single base class object if you use virtual inheritance:

class medium1:virtual public base{}m1;

class medium2: virtual public base{}m2;
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

This gets you down to two calls, but I think since you have double inheritance that's the best you'll get. If you eliminate the variable b in your base definition then you're there. http://codepad.org/pn016D7b

#include<stdlib.h> 

class base
{
public:
    base(){x=5;printf(" %i ",x);}
    int x;
}b;

class medium1:virtual public base 
{
public:
    medium1():base(){};
};

class medium2:virtual public base{};

class top:virtual public medium1,medium2{};


int main() {
    top ten;
    getchar();
    return 0;
}
MartyE
  • 636
  • 3
  • 7