I'm new to SO so let me know if I need to change anything. I did my best to be as thorough and provide example code. I know that many similar questions have been asked, I was unable to find one matching my specific problem though.
Furthermore, I'm aware that what I'm doing is not something one would do in 'real' code, I'm just trying to get a better understanding of r/l/p/x..values.
I have a base and a derived class, both having the default, copy, and move constructors. Now I want to have the copy constructor of the derived class calling the move constructor of the base class.
class Base
{
public:
Base(){ std::cout << "default base constructor called.\n"; }
Base(Base const &other) { std::cout << "copy base constructor called.\n"; }
Base(Base &&tmp) { std::cout << "move base constructor called.\n"; }
};
And basically the same for the derived class:
class Derived : public Base
{
public:
Derived(){ std::cout << "default derived constructor called.\n";}
Derived(Derived const &other)
:
Base(std::move(other)) // here I want to call Base(Base &&tmp)
{
std::cout << "copy derived constructor called.\n";
}
Derived(Derived &&tmp)
:
Base(std::move(tmp)) // correctly calls Base(Base &&tmp)!
{
std::cout << "move derived constructor called.\n";
}
};
So in my main function, I now want to call the copy constructor, which then calls the move constructor of the base class.
int main()
{
Derived der{};
Derived der_copy{ der };
Derived der_move{ std::move(der) };
}
The output I would get is this:
default base constructor called.
default derived constructor called.
copy base constructor called. <-- why not move?
copy derived constructor called.
move base constructor called.
move derived constructor called.
I was expecting the following:
default base constructor called.
default derived constructor called.
move base constructor called.
copy derived constructor called.
move base constructor called.
move derived constructor called.
So when I use std::move(tmp)
in the derived move constructor (so on Base &&tmp
) that the base move constructor is called, but when I use std::move(other)
in the derived copy constructor (so on Base const &other
) that the base copy constructor is called?
Tbh, this seems so strange that I'm afraid that I just made a mistake in my code, I checked everything multiple times but I can't seem to get the move base constructor called in the case above...
Thanks for your help!