1
class B
{
public:
    B(char c = 'a') : m_c(c) {}

public:
    fun();

private:
    char m_c;
};

class C: virtual public B
{ };

class D: virtual public B
{ };

class E
    : public C
    , public D
{ };

I am just wondering how “virtual” keyword is helping that class E have only one copy of class B? What virtual keyword does at “class C” so that it impacts its derived class later(As you can understand I am just trying to understand the basic working of virtual inheritance.I tried to find out the answer of this question but didn’t get it properly , if any one knows any good link even that can be of help.). In other words, what is the difference between

//1)
class C: virtual public B
{ };

//2)
class C: public B
{ };

If we don’t drive class C any further. Will there be any particular difference between 1) and 2) while creating its object.

pjain
  • 1,149
  • 2
  • 14
  • 28

2 Answers2

1

With the keyword virtual read "I will share". Without read "I will not share"

So with both C and D with both having virtual public B, both are prepared to share B

In the last example class C: public B, class C will not share - i.e. have its own copy.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
0

If we don’t d[e]rive class C any further. Will there be any particular difference between 1) and 2) while creating its object.

  • Construction of virtual bases happens before other base classes, even if those other bases are listed earlier in the class definition, and destruction happens afterwards. This doesn't affect your "C" classes as is, but if you added another base it could.

  • The default constructor of the version with virtual base class can never be "trivial", with various implications. For example, you can take the address of a trivially-constructed object's data member safely even if the constructor hasn't run yet (mainly relevant to dynamically loaded objects), there are some differences when used in unions etc..

Implementation details are not stipulated by the Standard, but it's possible that the class with virtual base will be slightly larger, and/or that construction and/or destruction may be marginally slower.

There are a few other quirks for longer derivation chains, e.g.: if an intermediate class's constructor's initialisation list specifies arguments for the virtual base's construction, they'll be ignored in favour of a more derived class's constructor, and you can omit construction calls from intermediate classes even if there's no default constructor in the virtual base.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252