I'm trying to call the base class move ctor explicitly through derived class move ctor but, surprise!, that actually calls the base class copy ctor NOT the base class move ctor.
I'm using std::move()
function on an object to be sure that the derived move ctor is being invoked!
The code:
class Base
{
public:
Base(const Base& rhs){ cout << "base copy ctor" << endl; }
Base(Base&& rhs){ cout << "base move ctor" << endl; }
};
class Derived : public Base
{
public:
Derived(Derived&& rhs) : Base(rhs) { cout << "derived move ctor"; }
Derived(const Derived& rhs) : Base(rhs) { cout << "derived copy ctor" << endl; }
};
int main()
{
Derived a;
Derived y = std::move(a); // invoke move ctor
cin.ignore();
return 0;
}
PROGRAM OUTPUT:
base copy ctor
derived move ctor
As you see, the base class move ctor is being forgotten, so how do I call it?
In the context of your
Derived
class the parameterrhs
clearly has a name. Thus, it must be an lvalue, it can't be an rvalue. However, theT&&
only binds to rvalues. If you want to call the base class's move constructor you need to use code like this:This will call the move constructor of
Base
and move theBase
portion ofrhs
. SinceBase
doesn't know anything about theDerived
members, theBase
move constructor won't move anything added byDerived
.