Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance in C++, "...is an ambiguous base of ..." error

Tags:

c++

As written in "The C++ Programming Language 3.Edition - Bjarne Stroustrup". We can use scope solution to prevent ambiguity errors. The basic program which is in below, when i use 3 layer scope in class mix an error occurs. But when i use 2 layer no problem. What is wrong? or is it something like design issue? The error is;

deneme.cpp: In constructor ‘mix::mix(std::__cxx11::string, int)’:
deneme.cpp:45:22: error: ‘plane’ is an ambiguous base of ‘mix’
    pervaneli::plane::engine=b;

I don't want to make a diamond model. I am happy with two base (plane) classes. The thing that i just want to learn why it gives error when i use 3 layer scope. Thanks.

Note: Version is g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609

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

class plane{
    protected:
    int speed;
    string name;
    public:
        int engine;
        void its_name(){
            cout<<name<<endl;
        }
        plane(int a=10000){
            engine=a;
        }

};

class pervaneli:public plane{
    public:
        pervaneli(string a="-"){
            name=a;
        }
        void belirle(int x){
            speed=x;
        }
};

class jet:public plane{
    public:
        jet(string a="-"){
            name=a;
        }
        void belirle(int x){
            speed=x;
        }
};

class mix: public pervaneli,public jet{
    public:
        mix(string a,int b){
            jet::name=a;
            pervaneli::name=a;
            pervaneli::plane::engine=b; //ambigous base error
            //pervaneli::engine=b; /*works fine*/
        } 
        void belirle(int x){
            jet::speed=x;
        }
};


int main()
    {
    mix a400m("Alp",9999);
    a400m.belirle(500);
    a400m.pervaneli::its_name();
    return 0;
    }
like image 408
al0s Avatar asked Mar 09 '23 04:03

al0s


2 Answers

From qualified_lookup

pervaneli::plane is the injected-class-name plane (the type).

so pervaneli::plane::engine is in fact plane::engine, which is ambiguous as you have two base class plane.

You cannot give full path to the member you want.

like image 159
Jarod42 Avatar answered Mar 25 '23 00:03

Jarod42


Public inheritance means is a relationship.
Reference: Effective C++: Item 32: Make sure public inheritance models “is-a.”

So pervaneli is a plane because of public inheritance. The class pervaneli already has the member variable engine in it because of is a relationship with plane.

By adding the scope of plane you are making it ambiguous for the compiler hence the error.

like image 44
ani627 Avatar answered Mar 25 '23 01:03

ani627