Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual methods on a virtual base class

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();
like image 547
sooniln Avatar asked Jul 07 '11 18:07

sooniln


People also ask

How do you call a virtual method from base class?

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.

What is virtual method in class?

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#.

What is difference between virtual base class and virtual function?

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.

What is virtual method in C++?

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.


1 Answers

It should not compile, the function foo will be ambiguous. Since A::foo() is pure virtual function, the ambiguity has to be resolved.

like image 61
Sharath Avatar answered Oct 21 '22 04:10

Sharath