In and Out of “default” in Classes

Lahiru Dilshan
2 min readOct 25, 2023
“default” keyword in c++

The default keyword is introduced in C++ 11 and it is used to tell the compiler to generate the class function independently if one is not declared in the class.

We all know that the compiler automatically generates different class functions for us by default. If the programmer uses the default keyword they will get understandable information about the lack of information on such functions.

This is a general form of using the default keyword for the class constructor.

class A
{
public:
A() = default;
virtual ~A() = default;
}

Functions that the “default” keyword applies

The default keyword can only be applied to special class functions. So, that cannot be used in every function in a particular class. Those functions are the functions which can be automatically generated by the compiler when the class is declared.

  • default constructor
  • copy constructor
  • move constructor
  • copy assignment operator
  • move assignment operator
  • destructor
Class Double
{
private:
double d;
public:
// default constructor
Double() = default;

// parameterized constructor - cannot use default keyword
Double(double value) : d(value)
{}

// copy constructor
Double(const Double&) = default;

// move constructor
Double(Double&&) = default;

// copy assignment operator
Double& operator=(const Double&) = default;

// move assignment operator
Double& operator=(const Double&&) = default;

// destructor
virtual ~Double() = default;

// other metods
double getDouble()
{
return d;
}
}

Can we use “virtual” and “default” both keywords at the same time?

Most of the developers are confused about using multiple keywords in the same function. This is also a frequent question.

class A
{
// can we use virtual and default in desctructor??
virtual ~A() = default;
}

Let’s discuss the meaning of these keywords.

  • virtual — This makes the destructor virtual. That means if the base class is inherited, the most derived class’s destructor gets called when a base pointer is deleted. The virtual keyword is what allows proper destructor polymorphism when inheriting the base class.
  • default — This asks the compiler to generate a default constructor implementation for this class. So the developer does not worry about the body of the destructor and the body will be empty and automatically generated.

If we use both these keywords means we want the destructor to be virtual for inheritance purposes, but don’t need to write a custom destructor body over ourselves.

--

--

Lahiru Dilshan

Geometry Maestro | Software & Mechanical Engineer | Crafting Virtual Realities 🚀