virtual base class
, virtual
Why is inheritance used?
I want to know what it means.
class Foo
{
public:
void DoSomething() { /* ... */ }
};
class Bar : public virtual Foo
{
public:
void DoSpecific() { /* ... */ }
};
virtual
Inheritance is meaningful in multiple inheritance.
virtual
By inheriting, multiple instances of the inherited class are prevented from being present in the hierarchy.
class A { public: void Foo() {} };
class B : public A {};
class C : public A {};
class D : public B, public C {};
If you look at the hierarchy of the code above briefly, you will see the diamond structure as below. D inherits B and C and both B and C inherit A.
A
/ \
B C
\ /
D
In this situation, ambiguity arises.
D d;
d.Foo(); // Is this B's foo? Is it C's foo?
virtaul
Inheritance is used in this situation.
If you specify virtual
when inheriting a class, the compiler creates only single instance
.
class A { public: void Foo() {} };
class B : public virtual A {};
class C : public virtual A {};
class D : public B, public C {};
This hierarchy now has only one instance of A. Anymore
d.Foo();
is unambiguous.
For more information, see here.
virtual
Inheritance is meaningful in multiple inheritance.
virtual
By inheriting, multiple instances of the inherited class are prevented from being present in the hierarchy.
class A { public: void Foo() {} };
class B : public A {};
class C : public A {};
class D : public B, public C {};
If you look at the hierarchy of the code above briefly, you will see the diamond structure as below. D inherits B and C and both B and C inherit A.
A
/ \
B C
\ /
D
In this situation, ambiguity arises.
D d;
D foo. () ; // This is b foo? C foo of?
virtaul
Inheritance is used in this situation.
If you specify virtual
when inheriting a class, the compiler creates only single instance
.
class A { public: void Foo() {} };
class B : public virtual A {};
class C : public virtual A {};
class D : public B, public C {};
This hierarchy now has only one instance of A. Anymore
d.Foo();
is unambiguous.
For more information, see here.
© 2024 OneMinuteCode. All rights reserved.