I have recently learned in school about the dreaded diamond.And I wrote a program using virtual inheritance to overcome the problems.I use g++ and I have the following errors with this program,

//doing to create an illustration for dreaded diamond
#include<iostream>
using namespace std;
class vehicle
{
 public:
 virtual void move()
 {
  cout<<"\n\nme moves";
 }
};
class car :public virtual vehicle
{
 public:
 virtual void move()
 {
  cout<<"\n\ni move on the road with screeching speed";
 }
};
class boat :public virtual vehicle
{
 public:
 virtual void move()
 {
  cout<<"\n\ni move on water";
 }
};
class watercar :public car,boat
{
 public:
 void go()
 {
  cout<<"\n\nI move on water or road based on your preference";
 }
};
int main()
{
 watercar obj;
 int a;
 obj.go();
 cin>>a;
 if(a==1)
 obj.move();
 else if(a==0)
 obj.move();
 return 0;
}

errors:

dreaded_diamond.cc:29: error: no unique final overrider for ‘virtual void vehicle::move()’ in ‘watercar’
dreaded_diamond.cc: In function ‘int main()’:
dreaded_diamond.cc:43: error: request for member ‘move’ is ambiguous
dreaded_diamond.cc:23: error: candidates are: virtual void boat::move()
dreaded_diamond.cc:15: error: virtual void car::move()
dreaded_diamond.cc:45: error: request for member ‘move’ is ambiguous
dreaded_diamond.cc:23: error: candidates are: virtual void boat::move()
dreaded_diamond.cc:15: error: virtual void car::move()

please help me
thanx in advance...

Well as the compiler says, and he is always right, call to move() is ambiguous.

if(a==1)
  obj.move(); //What is the difference between this.
else if(a==0)
  obj.move(); //And that.

You need a final override method when you have a dreaded-diamond. move() needs to be implemented in the watercar class, which ever way you want to implement it for your purpose, it needs an implementation because the compiler cannot choose for you which of the car::move() or boat::move() methods you want to call.

when i tried to call it using the period operator it says boat class is inaccessible

You need to change the name of watercar::go() to watercar::move(), that will address part of your issue since it will take care of the error mentioning the missing overload and inability to link.

Once that is corrected, you will still have intent errors that need addressing. To address them, you'll have to add a couple of scope resolutions. Specifically, you'll have to resolve watercar::move with boat or car to get the method you want in your if statement(s).

Your issue with accessing boat stems from not specifying a type of inheritance for it. Since you didn't specify the inheritance type, you have requested the default inheritance, which is private. You will need to add the public specifier to boat to open up access to the class' members.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.