Something that has been confusing me about virtual base class inheritance... Given the following classes:
class A
{
virtual void foo() = 0;
}
class B : virtual A
{
void foo() { /* do X */ }
}
class C : virtual A
{
void foo() { /* do Y */ }
}
class D : B, C
{
}
Will this compile? If so, what would be the result of the following code:
D d;
A* a = &d;
a->foo();
When you want to call a specific base class's version of a virtual function, just qualify it with the name of the class you are after, as I did in Example 8-16: p->Base::foo(); This will call the version of foo defined for Base , and not the one defined for whatever subclass of Base p points to.
A virtual method is a declared class method that allows overriding by a method with the same derived class signature. Virtual methods are tools used to implement the polymorphism feature of an object-oriented language, such as C#.
A virtual function is a member function of base class which can be redefined by derived class. A pure virtual function is a member function of base class whose only declaration is provided in base class and should be defined in derived class otherwise derived class also becomes abstract.
A virtual function in C++ is a base class member function that you can redefine in a derived class to achieve polymorphism. You can declare the function in the base class using the virtual keyword.
It should not compile, the function foo will be ambiguous. Since A::foo() is pure virtual function, the ambiguity has to be resolved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With