0

I'm trying to understand what exactly purpose of a virtual specifier in base class. As said in the c++14 working draft we have:

For each distinct base class that is specified virtual, the most derived object shall contain a single base class subobject of that type.

From this quote I'm assume that if we create an instance c of class C which is a derived class for A and B we're create an objects of A and B implicitly.

Question: How can I access to an instances of a base classes via an instance of derived class?

2 Answers2

0

An object of class struct C : A, B {}; contains two base subobjects, one of type A and one of type B. You can access them "directly":

void foo(A &);
void bar(B &);

C c;
foo(c);   // accesses the A-subobject
bar(c);   // accesses the B-subobject

You can also say static_cast<A&>(c) and static_cast<B&>(c) explicitly, though this is not often needed. You sometimes need to disambiguate names, though:

struct A { void f(); };
struct B { void f(); };
struct C : A, B { void f(); };

C c;

c.f();     // calls the member "f" of C
c.A::f();  // calls the member "f" of the A-base subobject of c
c.B::f();  // calls the member "f" of the B-base subobject of c

All this is not really related to the concept of virtual inheritance, which says that there is only relevant base subobject, even if it is referred to through multiple distinct inheritances:

struct V {};
struct A : virtual V {};
struct B : virtual V {};
struct C : A, B {};

In this last example, an object C c has only one base subobject of type V, not two, and the V-base subobjects of the A- and B-base subobjects of c see the same V base subobject. The virtual base is "shared" across the inheritance hierarchy.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0

virtual specifier is not related to accessing base sub-object, rather number of base sub-object in derived object. You can access base sub-object even if the base is not virtual. virtual is here to solve other problems like diamond inheritance problem

Rakib
  • 7,435
  • 7
  • 29
  • 45