Categories

Jan 2 in C++

Q:

Deleted and Defaulted Functions

1 Answer

Jan 2

A function in the form:

struct A

{

A()=default; //C++11

virtual ~A()=default; //C++11

};

is called a defaulted function. The =default; part instructs the compiler to generate the default implementation for the function. Defaulted functions have two advantages: They are more efficient than manual implementations, and they rid the programmer from the chore of defining those functions manually.

The opposite of a defaulted function is a deleted function:

int func()=delete;

Deleted functions are useful for preventing object copying, among the rest. Recall that C++ automatically declares a copy constructor and an assignment operator for classes. To disable copying, declare these two special member functions =delete:

struct NoCopy

{

NoCopy & operator =( const NoCopy & ) = delete;

NoCopy ( const NoCopy & ) = delete;

};

NoCopy a;

NoCopy b(a); //compilation error, copy ctor is deleted

Click here to read more about C++
Click here to read more about Insurance

Related questions

Madanswer
Jan 2 in C++
Mar 17 in C++
Jul 16, 2019 in C++
...