1

I am trying to create a new class in my program which is being extended from two inbuilt classes in a framework.

class Node{
    setPosition();
    draw();
};

class Rectangle{
    setPosition();
    draw();
};

class CustomShape : public Node, public Rectangle{

};

In main program, if I try to write something like CustomShape a and

a.setPosition();
a.draw();

I get compile time errors with ambiguous calls. How can I resolve this?

user2672165
  • 2,986
  • 19
  • 27
user1240679
  • 6,829
  • 17
  • 60
  • 89
  • 3
    What do you want to happen upon the call to `a.draw();`? – n. m. could be an AI Dec 23 '12 at 17:14
  • 1
    Duplicate of http://stackoverflow.com/questions/6845854/c-multiple-inheritance-function-call-ambiguity – Ali Dec 23 '12 at 17:15
  • 1
    This smells of bad design. Whatever you do don't unleash it on the world. – Ali Dec 23 '12 at 17:17
  • @Ali: Those `Node` and `Rectangle` classes come from a framework which I can't modify. I need to extend those classes and create my own functionality. Would there be another way to do that? – user1240679 Dec 23 '12 at 17:19
  • @user1240679 You would derive from only one class and use containership for the other. In other words, You have to decide if CustomShape is a Rectangle that contains(uses) a Node Or if CustomShape is a Node that contains(uses) a Rectangle. It can be only one of Node or Rectangle concretely depending on what you want CustomShape to do. Think from outside the box. How would users of CustomShape use it first? as Node or as Rectangle. – Ali Dec 23 '12 at 17:23

1 Answers1

3

Add explicit qualifications:

a.Node::setPosition();
a.Rectangle::setPosition();

a.Node::draw();
a.Rectangle::draw();

Alternatively you can insert a cast:

static_cast<Node&>(a).setPosition();

But that's less attractive.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • Great. But can I somehow shorten the usage of class names `Node` and `Rectangle` here? – user1240679 Dec 23 '12 at 17:16
  • @user1240679: You can add new member functions to `CustomShape` like `nodeSetPosition() { Node::setPosition(); }` if that helps... – Kerrek SB Dec 23 '12 at 17:33