-1

Possible Duplicate:
In C++, what is a virtual base class?

In this code when an object of DR is created, the string "Hello World" should be printed 4 times, instead it is printed just 3 times.Why is it so ? From what I guess it is because of the mid1 and mid2 being virtually inherited. Can somebody explain me what happens when we virtually inherit a class and more importantly when it is useful and why ?

#include <iostream>

struct BS
{
  BS()
  {
    std::cout << "Hello World" << std::endl;
  }
  unsigned int color;
};

struct mid1 : virtual public BS { };
struct mid2 : virtual public BS { };
struct mid3 : public BS { };
struct mid4 : public BS { };

struct DR : public mid1, public mid2, 
            public mid3, public mid4 { };

int main(int argc, char** argv) 
{ 
  DR d;
  return 0; 
}
Community
  • 1
  • 1
jairaj
  • 1,789
  • 5
  • 19
  • 32

1 Answers1

7

Let's look at a simplified example:

class base {};

class mid1 : public base {};
class mid2 : public base {};

class derived1 : public mid1, public mid2;

class mid1a : virtual public base {};
class mid2a : virtual public base {};

class derived2 : public mid1a, public mid2a {};

If we draw object diagrams for these, we get something like this:

enter image description here

When the intermediate classes use virtual inheritance, the derived class contains only a single instance of the base class, instead of a separate instance from each intermediate class.

In your case, that leads to three instances of the base class instead of four.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111