Acessing to a base subobject and virtual specifier c++
This question already has an answer here:
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.
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
上一篇: 访问受保护的基类的构造函数
下一篇: 访问基础子对象和虚拟说明符c ++