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?

5
  • 3
    What do you want to happen upon the call to a.draw();? Commented Dec 23, 2012 at 17:14
  • 1
    Duplicate of stackoverflow.com/questions/6845854/… Commented Dec 23, 2012 at 17:15
  • 1
    This smells of bad design. Whatever you do don't unleash it on the world. Commented Dec 23, 2012 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? Commented Dec 23, 2012 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. Commented Dec 23, 2012 at 17:23

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Great. But can I somehow shorten the usage of class names Node and Rectangle here?
@user1240679: You can add new member functions to CustomShape like nodeSetPosition() { Node::setPosition(); } if that helps...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.