Tuesday 9 April 2019

c++ - simple virtual inheritance & pure virtual method program






CORRECTION :



I edited two line from:




1) "class circle : public shape" to "class circle : public virtual shape"



2)"class square : public shape" to "class square : public virtual shape"



And yes , i am trying to have only one instance of Shape class for the shapes class , while defining the method draw differently inside Circle class and Square class






I am trying to do a simple inheritance program , but it gave me the following error:




*error C2250: 'shapes' : ambiguous inheritance of 'void shape::draw(void)'
*IntelliSense: override of virtual function "shape::draw" is ambiguous



-->this code resembles the solution of the diamond problem. I don't get why i see this error.



Here is the code:



    #include
using namespace std;
class shape
{

public:
shape()
{
cout << "shape created" << endl;
}
virtual void draw()=0;


};






    class circle : public virtual shape
{
public:
circle()
{
cout << "circle created" << endl;
}

virtual void draw()
{
cout << "this is a circle" << endl;
}
};





    class square : public virtual  shape

{
public:
square()
{
cout << "square created" << endl;
}
virtual void draw()
{
cout << "this is a square" << endl;
}

};





    class shapes : public  circle, public  square
{
public:
shapes()
{

cout << "shapes created" << endl;
}
};





    void main()
{
shapes e;

cout << "-------------" << endl;
system("pause");
}

Answer



(Moving from comment to answer)



It appears you intended to inherit virtually from shape, and then provide your own draw function in shapes



Inherit virtually like so:




class circle : public virtual shape //and same for class square


Then in shapes:



class shapes : public  circle, public  square
{
public:
shapes()

{
cout << "shapes created" << endl;
}

virtual void draw() //'virtual' is optional here
{
circle::draw();
square::draw();
}
};



Live Demo



Edit



Using virtual inheritance in your case is not strictly necessary per se, because your base is abstract (only pure virtual methods). However, if your use case is that the base class implements methods, then you will definitely want to use virtual inheritance. (Thanks @vsoftco)



This is because virtual inheritance guarantees that only one base class instance will be inherited into shapes, whereas in C++ by default in each derived class gets its own instance of a base, and so shapes would actually inherit TWO instances of shape, one through circle and one through square. At that point, calling any base class function from a shapes object becomes ambiguous because the compiler wouldn't be certain which instance you meant to call it from.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...