Search code examples
c++multiple-inheritancevirtual-functionsambiguousname-lookup

Why is this piece of code "not ambigious!" - virtual functions


Why is the below code not ambiguous and how it works fine?

#include <QCoreApplication>
#include <iostream>
using namespace std;

class Shape{
public:
    virtual void drawShape(){
        cout << "this is base class and virtual function\n";
    }
};

class Line : public Shape{
public:
    virtual void drawShape(){
        cout << "I am a line\n";
    }
};

class Circle : public Shape{
public:
    virtual void drawShape(){
        cout <<" I am circle\n";
    }
};

class Child : public Line, public Circle{
public:
    virtual void drawShape(){
        cout << "I am child :)\n";
    }
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    //Shape *s;
    //Line l;
    Child ch;
    //s = &l;
    //s = &ch;
    ch.drawShape(); // this is ambiguous right? but it executes properly!
    //s->drawShape();
    return a.exec();
}

Solution

  • It isn't ambiguous because Child defines it's own override of drawShape, and ch.drawShape will call that function. If Child did not provide an override of drawShape then the call would be ambiguous.