Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need to use virtual ~A() = default; instead of virtual ~A() {} in C++11?

In Stack Overflow post Checking the object type in C++11, I have the comment:

In C++11 you'll actually want to do virtual ~A() = default; Otherwise, you'll lose the implict move constructors.

What is virtual ~A() = default; for? How come implicit move constructors lost with virtual ~A() {}?

like image 324
prosseek Avatar asked Jun 20 '13 19:06

prosseek


People also ask

Why do we use virtual function in C++?

A virtual function in C++ helps ensure you call the correct function via a reference or pointer. The C++ programming language allows you only to use a single pointer to refer to all the derived class objects.

Why do we need virtual function?

Why use virtual functions. We use virtual functions to ensure that the correct function is called for an object, regardless of the reference type used to call the function. They are basically used to achieve the runtime polymorphism and are declared in the base class by using the virtual keyword before the function.

Is it necessary to override a virtual method in C++?

It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used.

Why is virtual method called virtual?

'virtual function' means a member function where the specific implementation will depend on the type of the object it is called upon, at run-time. The compiler and run-time support of the language contrive to make this happen. The keyword 'virtual' in C++ was taken from Simula, which had impressed Bjarne Stroustrup.


1 Answers

The comment is not correct.

Both:

virtual ~A() = default; 

and

virtual ~A() {} 

are user declared. And the implicit move members are inhibited if the destructor is user declared.

[dcl.fct.def.default]/p4 discusses user-declared and user-provided special members:

A special member function is user-provided if it is user-declared and not explicitly defaulted or deleted on its first declaration.

like image 166
Howard Hinnant Avatar answered Oct 01 '22 01:10

Howard Hinnant