Consider:
// member data omitted for brevity
// assume that "setAngle" needs to be implemented separately
// in Label and Image, and that Button does need to inherit
// Label, rather than, say, contain one (etc)
struct Widget {
Widget& move(Point newPos) { pos = newPos; return *this; }
};
struct Label : Widget {
Label& setText(string const& newText) { text = newText; return *this; }
Label& setAngle(double newAngle) { angle = newAngle; return *this; }
};
struct Button : Label {
Button& setAngle(double newAngle) {
backgroundImage.setAngle(newAngle);
Label::setAngle(newAngle);
return *this;
}
};
int main() {
Button btn;
// oops: Widget::setText doesn't exist
btn.move(Point(0,0)).setText("Hey");
// oops: calling Label::setAngle rather than Button::setAngle
btn.setText("Boo").setAngle(.5);
}
Any techniques to get around these problems?
Example: using template magic to make Button::move return Button& or something.
edit It has become clear that the second problem is solved by making setAngle virtual.
But the first problem remains unsolved in a reasonable fashion!
edit: Well, I guess it's impossible to do properly in C++. Thanks for the efforts anyhow.
See Question&Answers more detail:os