Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why class derived from non-movable class is itself move constructible? [duplicate]

According to cppreference, deriving from a non-movable class should make a derived class non-movable, too. Then why does std::is_move_constructible_v return true for the derived class?

class NonMovable{
    public:
        NonMovable(const NonMovable&) = default;
        NonMovable(NonMovable&&) = delete;
        
        NonMovable& operator = (const NonMovable&) = default;
        NonMovable& operator = (NonMovable&&) = delete;
        
        NonMovable() = default;
};

class Derived : public NonMovable{};

int main(){
    std::cout << std::is_move_constructible_v<NonMovable> << "\n"; // 0
    std::cout << std::is_move_constructible_v<Derived> << "\n"; // 1
}
like image 850
capi1500 Avatar asked Jun 07 '21 23:06

capi1500


People also ask

Is move constructor automatically generated?

No move constructor is automatically generated.

How are constructors of the derived classes executed?

The constructor of the derived class receives the entire list of required values as its argument and passes them on to the base constructor in the order in which they are declared in the derived class. A base class constructor is called and executed before executing the statements in the body of the derived class.

What is class derived?

What is a Derived Class? A derived class is a class that is constructed from a base class or an existing class. It has a tendency to acquire all the methods and properties of a base class. It is also known as a subclass or child class.


1 Answers

The key clause appears to be the following:

Copy/move constructors [class.copy.ctor]

...

A defaulted move constructor that is defined as deleted is ignored by overload resolution. [ Note: A deleted move constructor would otherwise interfere with initialization from an rvalue which can use the copy constructor instead. — end note ]

Emphasis mine. The deleted move constructor is simply excluded from overload resolution, and the derived class's constructor ends up seleting the base class's copy constructor instead of the move constructor.

like image 55
Sam Varshavchik Avatar answered Oct 23 '22 03:10

Sam Varshavchik