Let's consider the following class to be extended:
struct A {
int x, y;
A(int x, int y) : x(x), y(y) {}
};
You can inherit from this class or write a wrapper class which contains an instance of this class. In most cases, inheritance is the way to go, as a wrapper class isn't an A but it wraps (contains) an A.
With C++11 move semantics, promoting an instance A
to a subclass B
(inheriting A
) will be efficient and doesn't require to copy the instance A
:
class B : public A {
public:
B (A &&a) : A(a), someOtherMember(a.x + a.y) {}
// added public stuff:
int someOtherFunction() const { return someOtherMember; }
private:
// added private stuff:
int someOtherMember;
};
Full code with example: http://ideone.com/mZLLEu
Of course the function I added is a bit silly (and the member even more, since it doesn't respect further changes of the original members x
and y
), but you should get an idea of what I want to demonstrate.
Note the constructor B (A &&a)
which is something I call "promote constructor" (this is not a standard term). Normally, B (B &&b)
is a move constructor, which moves the contents of the provided B
instance into a new B
about to be constructed. I use the move semantics to move an instance of A
(which has been returned by another function) into the super-class A
of B
.
Effectively, you can promote A
to B
while making it possible to use a B
as an A
.
In contrast to Soonts' answer, my solution also works with added virtual tables, since it doesn't rely on unsafe pointer casting.