Why are virtual functions preferable over derived class objects? - c++

So I'm new to learning about virtual functions, and I'm following online tutorials and I can't seem to find an answer to my question. I want to ask why using virtual functions below by setting base class objects to point to derived class objects, is preferable to just using the derived class objects themselves to access the functions?
It seems that I get the same output either way, and it seems creating base class objects and virtual functions are extra steps. I saw a similar example to this on an online tutorial which claimed virtual functions made coding easier but I don't quite see the benefit in this example?
I read online that:
The main advantage of virtual functions are that they directly support object oriented programming. When you declare a function as virtual you're saying that exactly what code is executed depends on the type of the object you call it against.
But it seems this is already the case using derived objects, and that creating base class objects is unnecessary? I'm sure that I'm missing something obvious so I would really appreciate any help. I showed an example code I wrote below which is similar to what I've seen when detailing virtual functions:
#include <iostream>
using namespace std;
//////////////////////////////////////////////////////
//base class
class Shape {
public:
virtual void draw()=0; //pure virtual function
};
//derived classes
class Square : public Shape {
public:
void draw() {
cout << "Draw square" << endl;
}
};
class Circle : public Shape {
public:
void draw() {
cout << "Draw circle " << endl;
}
};
//////////////////////////////////////////////////////
int main()
{
Square so; //create derived class objects
Circle co;
Shape* shape1 = &so; //setting base class objects as pointers to derived objects
Shape* shape2 = &co;
shape1->draw(); //using base class objects to access derived class
shape2->draw();
so.draw(); //using derived class objects
co.draw();
}

The huge benefit that you get for using the base class pointer type and virtual functions is that you can have one single list that contains several different types of Shape and you can process them all in a single function where they will all have different behaviors due to their derived types.
As an example, I modified your code by adding the function DrawAllShapes that takes in a vector<Shapes*>&. (Be careful of using raw pointers. You really should use vector<std::unique_ptr<Shape>>&here or something like that.
You have incredible flexibility with this pattern that lets you call the same function on a collection of base class pointer objects but results in different behavior for every object in the collection depending on its derived type.
#include <iostream>
#include <vector>
using namespace std;
//////////////////////////////////////////////////////
//base class
class Shape {
public:
virtual void draw() = 0; //pure virtual function
};
//derived classes
class Square : public Shape {
public:
void draw() {
cout << "Draw square" << endl;
}
};
class Circle : public Shape {
public:
void draw() {
cout << "Draw circle " << endl;
}
};
void DrawAllShapes(std::vector<Shape*>& shapes) {
for (int i = 0; i < shapes.size(); ++i) {
shapes[i]->draw();
}
}
//////////////////////////////////////////////////////
int main()
{
std::vector<Shape*> shapeVec{ new Square, new Circle, new Square, new Square, new Circle };
DrawAllShapes(shapeVec);
system("pause");
}
Also, imagine if you were using a prebuilt graphical library that already had a Shape class and several shapes defined. What if you wanted to add your own new type of Shape and have it work perfectly with all of the library's functions? All you would have to do is create your own derived class and implement all of the necessary virtual functions exposed by the library's Shape class and then you've literally extended the library beyond its original capabilities.

Related

How to create a new pointer to a derived class which type is unknown at compile time in C++? [duplicate]

This question already has answers here:
Cloning C++ class with pure virtual methods
(4 answers)
Closed 4 years ago.
I have a code where there are some pointers to derived classes of the same base class. At one point I need to create another pointer to one of this derived classes, but I don't know at compile time to which class it will point to.
Here an example of the code:
#include <iostream>
using namespace std;
class Polygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; };
virtual int area() = 0;
};
class Rectangle: public Polygon {
public:
int area()
{ return width*height; }
};
class Triangle: public Polygon {
public:
int area()
{ return width*height/2; }
};
int main () {
Rectangle* rect = new Rectangle;
Triangle* trgl = new Triangle;
Polygon* ppoly;
trgl->set_values (4,5);
ppoly = trgl;
cout << ppoly->area() << '\n';
trgl->set_values (8,5);
cout << ppoly->area() << '\n';
return 0;
}
Writing the code as above, 'ppoly' points to the same memory as trgl, so the 2 lines cout << ppoly->area() << '\n' print different results because I have changed width of the pointer trgl. In my codeI don't want this behaviour, but I would like that ppoly is a new pointer of the same type of trgl.
I have tried to use Polygon* ppoly = new Polygon, but returns me an error at compile time:
error: invalid new-expression of abstract class type 'Polygon'
How can I correct the software?
What you are asking for is virtual (copy) constructor i.e. a clone() function.
Obviously, you can't instantiate a derived class using nothing but base-class-related constructs. But a base-class pointer still has a derived-class instance behind it, and it can encapsulate the "ability" to construct another instance.
This idiom is known as a Virtual Constructor - and it is not even difficult to implement. In a nutshell, you'll have a non-static virtual method which constructs a new instance on the heap, and is usable from the base class. It will look something like:
Polygon* poly = get_a_poly_which_really_is_some_derived_class();
Polygon* another_poly = poly->create();
Notes:
I just noticed that Cloning C++ class with pure virtual methods is basically a clone and has similar answers.
I wouldn't recommend doing this unless you really need to. I'd guess there's probably a better alternative to resorting to virtual-constructing objects.
Instead of using raw pointers, use std::unique_ptr<Polygon> or std::shared_ptr<Polygon>.

Parent class referencing child variable

I have several similar classes inheriting from the same Base-Class/Interface (Base class 1), and they share a couple similar functions, but then also have their own distinct functions. They all also have their own member variables of different classes, and each of those inherits from the same Base-Class/Interface (Base class 2). Is it possible to define a variable in Base class 1, of type Base class 2, then in the actual implementation of classes using Base class 1, have the variable of type Base class 2 be its proper type. Kinda hard to explain, so simplified example below.
//Base-Class 1
class Shape
{
public Shape() {}
ShapeExtra m_var;
//The common functions
public GetVar(){ return m_var; }
}
class Circle : Shape
{
public Circle() { m_var = new CircleExtra(); }
public void CircleFunc()
{
m_var.CircleExtraFunc();
}
}
class Triangle : Shape
{
public Triangle() { m_var = new TriangleExtra(); }
public void TriangleFunc()
{
m_var.TriangleExtraFunc();
}
}
.
.
.
//Base_Class 2
class ShapeExtra
{
public ShapeExtra() {}
}
class CircleExtra : ExtraClass
{
public CircleExtra() {}
void CircleExtraFunc() {//Do stuff}
}
class TriangleExtra : ExtraClass
{
public TriangleExtra() {}
void TriangleExtra() {//Do stuff}
}
.
.
.
So, I need the m_var in the child classes to be kept it as its own unique version. Because right now (w/o the extra CircleExtra m_var;), the GetVar() works, but in CircleFunc, m_var is still type of ShapeExtra, and thus doesn't know that CircleExtraFunc exists. I could cast m_var each time I wanted to do that, but that is repetitive and not worth it in my real-world case. Is there a way to utilize the functions in unique classes based off of ShapeExtra, while keeping the GetVar() function in Shape?
Please ask questions if there is anything I left out.
Simply with inheritance and without using pointers it is not possible, as C++ is a statically-and-strictly-typed language.
You can inherit both the variable and the function, but you'll need to cast function return value.
You can also override the function to make it return the concrete type, but then you have to cast the variable inside the function.
You can also declare the same var with the concrete class in subclasses, but then you just hide the variable in the superclass and inherit nothing.
I'd rather go for a solution using templates. Make the type of the variable a template type and extend the template using a concrete type in subclasses. It'll work perfectly.
It's been a long time since I last programmed in C++ and I beg your pardon if there are errors in the following example. I'm sure you can easily make it work.
template <class S>
class Shape {
S m_var;
//......
public:
S var () {
return m_var;
}
//.......
}
class Circle: Shape <CircleExtra> {
// var method returns CircleExtra
//......
}
Edit:
Regarding some comment, to allow virtual invocation of the method, it is possible to use correlated return types. Something like the following example.
class Shape {
public:
virtual ShapeExtra *var () = 0;
}
template <typename SE>
class ConcreteShape: Shape {
public:
virtual SE *var() {
return &m_var;
}
// Constructor, etc.
private:
SE m_var;
}
Or some variation. Now concrete shapes can benefit from extending the template, as long as SE * is correlated with ShapeExtra * (the type parameter extends ShapeExtra). And you can vall the method transparently through Shape interface.
Using pointers, this is totally possible.
Using your example, you could do something like this:
#include <iostream>
#include <memory>
using namespace std;
//Extras
class ShapeExtra
{
public:
ShapeExtra() {}
void ShapeFunc() { std::cout << "Shape"; }
virtual ~ShapeExtra() = default; //Important!
};
class Shape
{
public:
std::unique_ptr<ShapeExtra> m_var;
//require a pointer on construction
//make sure to document, that Shape class takes ownership and handles deletion
Shape(ShapeExtra* p):m_var(p){}
//The common functions
ShapeExtra& GetVar(){ return *m_var; }
void ShapeFunc() {m_var->ShapeFunc();}
};
class CircleExtra : public ShapeExtra
{
public:
void CircleExtraFunc() {std::cout << "Circle";}
};
class Circle : public Shape
{
CircleExtra* m_var;
public:
Circle() : Shape(new CircleExtra()) {
m_var = static_cast<CircleExtra*>(Shape::m_var.get());
}
void CircleFunc()
{
m_var->CircleExtraFunc();
}
};
int main() {
Circle c;
//use the ShapeExtra Object
c.GetVar().ShapeFunc();
//call via forwarded function
c.ShapeFunc();
//call the circleExtra Function
c.CircleFunc();
return 0;
}
Test it on ideone
Note the use of pointers and a virtual destructor:
By using a virtual destructor in the ShapeExtra base class, you make it possible to destruct an object of any derived class, using a ShapeExtra*. This is important, because
by using a std::unique_ptr<ShapeExtra> instead of a plain C-pointer, we make sure that the object is properly deleted on destruction of Shape.
It is probably a good idea to document this behaviour, i.e. that Shape takes the ownership of the ShapeExtra*. Which especially means, that we do not delete CirleExtra* in the Circle destructor
I decided here to require the ShapeExtra* on construction, but its also possible to just use std::unique_ptr::reset() later and check for nullptr on dereferencing Shape::m_var
Construction order is this: On calling the constructor of Circle, we first create a new CircleExtra which we pass to Shape before finally the constructor of Circle is executed.
Destruction order is Circle first (was created last), then Shape which also destructs the ShapeExtra for us, including (via virtual function) the CircleExtra
I would recommend the following approach:
class ShapeExtra
{
public:
virtual ~ShapeExtra() { }
virtual void SomeCommonShapeFunc() { std::cout << "Shape"; }
};
class Shape
{
public:
virtual ShapeExtra &GetVar() = 0; // Accessor function.
};
Note that the class Shape does not have any data members at all. After that for each derived class you need:
class CircleExtra : public ShapeExtra
{
public:
void SomeCommonShapeFunc() { std::cout << "Circle"; }
};
class Circle : public Shape
{
CircleExtra m_var; // Data member with circle specific class.
public:
virtual ShapeExtra &GetVar() { return m_var; }
};
Implementation of virtual method in Circle will return reference to the base class ShapeExtra. This will allow using this extra in the base class.
Note that pointers and templates are not used at all. This simplifies the overall design.

Access child class' functions within parent class

I've been coding a simple board game to learn concepts of C++ in practice. I have implemented the board: it consists of tiles, each of which is a child class inheriting from a parent class. The board is a class that has a vector of the tiles.
There are several kinds of tiles. Some of them can be bought by players. There are several different kinds of buyable tiles as well with different properties, so I deemed it cute to make a base class TileOnSale for tiles that can be bought and make child classes of the actual types, two of which I have provided in the below code.
Now my problem is that how can I access the child members' functions not defined within the parent class (TileOnSale)? Board gets initialized with all kinds of different tiles, so I can extract a Tile from there using getTile(int location) function. However, this gets interpreted as just a Tile, not a TileOnSale or a StreetTile. I know of no way to grasp StreetTile's buildHouses function this way.
So, is there a robust, or even better, a neat way of doing this? Can I make a template or something to hold Tile objects that might be StreetTiles or StationTiles or something else that is a Tile?
Or should I just redesign the class structure?
Here's a bare bones code. I have tried to provide only what is needed for understanding the question. Also, originally Tile and Board were in their own header files. I decided it not necessary to show the Player class that has a vector of owned TileOnSale objects but which retains the exact same access problem as Board.
// Board.h
#include "Tile.h"
typedef vector<Tile> Tiles;
class Board
{
public:
Board();
~Board();
Tile getTile(int location);
private:
Tiles tiles;
};
// Tile.h
class Tile
{
public:
Tile();
~Tile();
protected:
tileType tile_type; // this is enum containing unique type
string description;
};
class TileOnSale : public Tile
{
public:
TileOnSale();
~TileOnSale();
virtual int getRent() const { return 0; };
};
class StreetTile : public TileOnSale
{
public:
StreetTile();
~StreetTile();
int getRent() override;
void buildHouses(int number);
private:
int houses;
};
class StationTile : public TileOnSale
{
public:
StationTile();
~StationTile();
int getRent() override;
};
EDIT: added a potentially clarifying comment to code.
You might want to take a look at the visitor pattern.
In essence, the visitor allows one to add new virtual functions to a family of classes without modifying the classes themselves; instead, one creates a visitor class that implements all of the appropriate specializations of the virtual function. The visitor takes the instance reference as input, and implements the goal through double dispatch.
The double dispatch means you are actually calling a virtual function twice: first on the subject which in turn polymorphically calls the visitor.
In your case there is just one method, namely building houses, but you might want to add others later (like drawing them on a screen for example). Given your current example you should add this method to Tile and StreetTile:
virtual void accept(Visitor& v) { v.visit(*this); }
This is the Visitor base class implementation:
class Visitor {
public:
virtual void accept(Tile& t) = 0;
virtual void accept(StreetTile& t) = 0;
};
After that you can implement a Builder class:
class Builder: public Visitor {
private:
int numberOfHouses;
public:
Builder(int n): numberOfHouses(n) {}
virtual void accept(Tile& t) {}
virtual void accept(StreetTile& t) {
t.buildHouses(numberOfHouses);
}
};
After that all you have to do is construct such a builder, and call it on every tile in your vector of tiles:
Builder b(10);
for (Tile tile : tiles) {
tile.accept(b);
}
A Simple way is to add a unique id (enum or string) to each type. The player class can ask for the type (defined in the base class) and cast to the derived class accordingly.
Since it needs to call a function on the derived (e.g. specialized) class it has the knowledge to perform the cast.
Having a type ID is also nice for debugging purposes.

How can I iterate over a vector of base class objects?

I have an problem where we need to have a number of shapes, such as a Circle and Square which can be position on a flat, 2 dimensional plane. All shapes, such as Circle and Square inherit from an abstact base class Shape; as such I have a vector of pointers to shapes.
However, I need to be able to iterate over the plane and find any shapes which collide, such that they are intersecting or touching. If I get a shape from the vector, I don't know if it is a Square or a Circle because it has been sliced to the Shape base class.
How would I be best solving this problem?
#ifndef Plane_h
#define Plane_h
#include <vector>
#include "Shape.h"
class Plane {
public:
Plane(std::vector<Shape*>);
Plane(const Plane&);
~Plane();
void add(Shape*);
std::vector<Shape*> all() const;
protected:
std::vector<Shape*> shapes;
};
#endif
Your classes have not been sliced. This would result in a sliced object:
vector<Shape> vec;
Circle circ;
vec.push_back(circ);
http://en.wikipedia.org/wiki/Object_slicing
In your instance the instantiated objects remain whole and the pointers point to whole objects - but it is almost certainly true that in order to calculate intersections you will need to do some downcasting. While this is to be done as little as possible it's not a crime in itself.
Your best bet would be to provide a method in the base class to return a value indicating the object type - maybe use an enumeration - and use that to downcast a particular Shape pointer or reference to a pointer/reference to the correct derived type.
An abstract method in the base Shape class like bool Intersects( const Shape& obj ) could be overridden by the derived classes, the overrides downcasting the parameter to the correct derived type.
Alternatively you might prefer to provide a global/static method taking two shapes, or privately implement that method and call it from the instance method Intersects()
( Detecting the intersections is not exactly a trivial task. :-) )
You have to use polymorphism. Add a virtual method on your Shape class:
class Shape {
...
virtual bool intersects(Shape const* otherShape);
...
}
Then you implement it for each different shape. Then if it's used like:
Shape* A = getShapeA();
Shape* B = getShapeB();
if (A->intersects(B))
doSomething();
The correct version is called, i.e if A is a Circle, Circle::intersects is called. But in there, you still don't know what shape B actually is. You can find this out by trying to do a dynamic cast:
Circle* circle = dynamic_cast<Circle*>(otherShape);
if (circle)
intersectsCircle(circle);
Here is another method, that does not need dynamic casts (or any explicit cast at all), or an ugly enum listing the subclasses. It is based on double dispatch, which basically works by going through two virtual methods in order to determine the types of the two objects you want to work on.
#include <iostream>
using namespace std;
class Circle;
class Square;
struct Shape
{
virtual void intersect(Shape* otherShape) = 0;
virtual void intersect(Circle* otherCircle) = 0;
virtual void intersect(Square* otherSquare) = 0;
};
struct Circle : public Shape
{
virtual void intersect(Shape* otherShape)
{
otherShape->intersect(this);
}
virtual void intersect(Circle* otherCircle)
{
cout << "Intersecting Circle with Circle" << endl;
}
virtual void intersect(Square* otherSquare)
{
cout << "Intersecting Circle with Square" << endl;
}
};
struct Square : public Shape
{
virtual void intersect(Shape* otherShape)
{
otherShape->intersect(this);
}
virtual void intersect(Circle* otherCircle)
{
otherCircle->intersect(this);
}
virtual void intersect(Square* otherSquare)
{
cout << "Intersecting Square with Square" << endl;
}
};
int main()
{
Circle circle;
Square square;
circle.intersect(&square);
Shape* shapeA = &circle;
Shape* shapeB = &square;
shapeA->intersect(shapeA);
shapeA->intersect(shapeB);
shapeB->intersect(shapeA);
shapeB->intersect(shapeB);
}
Note that here you still have to list all possible subclasses within the base class, but in this case in the form of overloads of the intersect for each base class. If you fail to add all (say, you make a class Triangle : public Shape, but no Shape::intersect(Triangle*)), you end up with infinite call loops.
Also note that in this example I did a 'triple' dispatch, so I don't have to implement the logic to intersect a Circle with a Square twice.

Multiple inheritance in C++ leading to difficulty overriding common functionality

In a C++ physics simulation, I have a class called Circle, and Square. These are Shapes, and have a method called push(), which applies force to it. There is then a special case of Circle, call it SpecialCircle, in which push() should exhibit slightly different properties. But in fact, there is also SpecialSquare() which should exhibit the same force properties. So I'd like to have an abstract base class called Shape which takes care of Circles and Squares, but then I'd also like an abstract base class called Special, which applies special properties to force().
What's the best way to design this class structure?
So far, I've got:
class Shape {
virtual void push();
};
class Circle : public Shape {};
class Square : public Shape {};
class Special {
virtual void push();
};
class SpecialCircle : public Circle, Special {};
class SpecialSquare : public Square, Special {};
Of course, the above won't compile, since Special::push() and Shape::push() conflict. I get "error: request for member ‘push’ is ambiguous", as expected.
How can I re-organize my class structure so that Circle and Square can share certain properties with each other, but SpecialCircle and SpecialSquare can still inherit from Shape, and also inherit modified functionality from Special?
Thanks.
ps., is this the diamond inheritance problem?
Another solution (it may or may not fit your needs, it depends on the details of your implementation):
Have the class Behavior, and let NormalBehavior and SpecialBehavior inherit from it.
Have the class Shape, and let Square and Circle inherit from it. Let Shape be an aggregate type, with a Behavior member (i.e. you pass a Behavior object to the various Shape constructors). In other words, let a Shape have a Behavior.
Delegate the actual differences in the behavior of shapes to methods of the Behavior hierarchy.
Conversely, you can:
Have the class PhysicalObject, and let NormalObject and SpecialObject inherit from it;
Have the class Shape, and let Square and Circle inherit from it;
Let a PhysicalObject have a Shape.
Prefer aggregation over inheritance. This is an application of the Bridge pattern. The advantage of this strategy with respect to having Square, SpecialSquare, Circle, and SpecialCircle, is that tomorrow you'll have to add Rectangle, Hexagon and so on, and for each shape you add you'll have to implement two classes (duplicated code is evil); this is, in my opinion, the real issue that Bridge addresses.
It's said that every problem in software can be solved by adding an additional layer of indirection.
Herb Sutter has an excellent article on how to solve your problem: Multiple Inheritance - Part III
In short, you use intermediate classes to 'rename' the virtual functions. As Herb says:
Renaming Virtual Functions
If the two inherited functions had different signatures, there would be no problem: We would just override them independently as usual. The trick, then, is to somehow change the signature of at least one of the two inherited functions.
The way to change a base class function's signature is to create an intermediate class which derives from the base class, declares a new virtual function, and overrides the inherited version to call the new function
Here's a long example using your classes:
class Shape {
public:
virtual void push() = 0;
};
class Circle : public Shape
{
public:
void push() {
printf( "Circle::push()\n");
}
};
class Square : public Shape
{
public:
void push() {
printf( "Square::push()\n");
}
};
class Special {
public:
virtual void push() = 0;
};
class Circle2: public Circle
{
public:
virtual void pushCircle() = 0;
void push() {
pushCircle();
}
};
class Square2: public Square
{
public:
virtual void pushSquare() = 0;
void push() {
pushSquare();
}
};
class Special2 : public Special
{
public:
virtual void pushSpecial() = 0;
void push() {
pushSpecial();
}
};
class SpecialCircle : public Circle2, public Special2
{
public:
void pushSpecial() {
printf( "SpecialCircle::pushSpecial()\n");
}
void pushCircle() {
printf( "SpecialCircle::pushCircle()\n");
}
};
class SpecialSquare : public Square2, public Special2
{
public:
void pushSpecial() {
printf( "SpecialSquare::pushSpecial()\n");
}
void pushSquare() {
printf( "SpecialSquare::pushSquare()\n");
}
};
int main( int argc, char* argv[])
{
SpecialCircle sc;
SpecialSquare ss;
// sc.push(); // can't be called - ambiguous
// ss.push();
sc.pushCircle();
ss.pushSquare();
Circle* pCircle = &sc;
pCircle->push();
Square* pSquare = &ss;
pSquare->push();
Special* pSpecial = &sc;
pSpecial->push();
pSpecial = &ss;
pSpecial->push();
return 0;
}
Rather than thinking of code reuse through inheritance, the use of mixins will give you the code reuse you want without the problems of multiple inheritance.
If you are unfamiliar with the technique, do a search on SO or Google. Make sure you search for both "mixin" and "Curiously Recurring Template Pattern". There are heaps of great articles around to get you started.
When you have to inherit from multiple interfaces with the same method the compiler can't tell which one are you trying to call, you can fix this by overriding such method and call the one you want.
class SpecialCircle : public Circle, Special {
public:
virtual void push() { Special::push(); }
};
class SpecialSquare : public Square, Special {
public:
virtual void push() { Special::push(); }
};
But in this case I think the correct OO approach is to factor out the push behavior in its own class, like Federico Ramponi have suggested.
Have a SpecialShape from Shape and SpecialCircle and SpecialSquare from SpecialShape.
Well, if the special and normal circles can be both applied forces to, and the special circle has another method that applies special forces, why not have two interfaces and two methods?
struct Applicable {
virtual ~Applicable() { }
// if it applies force, better be explicit with naming it.
virtual void applyForce() = 0;
};
struct SpecialApplicable {
virtual ~SpecialApplicable() { }
virtual void applySpecialForce() = 0;
};
struct Shape {
virtual ~Shape() { }
Size getSize();
Point getPosition();
// ...
};
struct Circle : Shape, Applicable {
virtual void applyForce() { /* ... */ }
}
struct SpecialCircle : Circle, SpecialApplicable {
virtual void applySpecialForce() { /* .... */ }
};
If it doesn't make sense if there is both a special and a normal apply method (which the name of the class - SpecialCircle - suggests), then why not do even this:
struct Circle : Shape, Applicable {
virtual void applyForce() { /* ... */ }
}
struct SpecialCircle : Circle {
// applies force, but specially
virtual void applyForce() { /* .... */ }
};
You can also put the applyForce into the Shape class. It also depends on the environment in which those classes are used. What, in any case, you really should avoid is having the same method in two base classes that appear in two difference base-lattices. Because that inevitable will lead to such ambiguity problems. The diamond inheritance is when you use virtual inheritance. I believe there are other good answers on stackoverflow explaining that. It isn't applicable for your problem, because the ambiguity arises because the method appears in two base class sub-objects of different types. (It only solves such cases where the base classes have the same type. In those cases, it will merge the base classes and there will only be one base class sub-object contained - inherited by virtual inheritance)