Table of contents
1.
Introduction
2.
Syntax of Default Constructors in C++
3.
Example of Default Constructor Syntax
4.
Features of Default Constructors in C++
4.1.
C++
5.
Types of Default Constructors in C++
5.1.
1. Implicitly-Declared Default Constructor:
5.2.
2. Implicitly-Defined Default Constructor
5.3.
C++
5.4.
3. Deleted Implicitly-Declared Default Constructor
5.5.
4. Trivial Default Constructor
5.6.
5. Eligible Default Constructor
5.6.1.
Example 1: Constructor with no parameters
5.6.2.
Example 2: Constructor with default arguments
5.6.3.
Example of using an eligible default constructor
6.
Examples of Default Constructors in C++
6.1.
Example 1: Basic Initialization
6.2.
C++
6.3.
Example 2: Array of Objects
6.4.
C++
6.5.
Example 3: Dynamic Object Creation
6.6.
C++
7.
Frequently Asked Questions
7.1.
Why use a default constructor in C++?
7.2.
Can a default constructor in C++ take arguments?
7.3.
Is it possible to disable the default constructor in C++?
7.4.
In C++, when is the default constructor automatically called?
8.
Conclusion
Last Updated: Oct 30, 2024
Easy

Default Constructor in C++

Author Gaurav Gandhi
0 upvote

Introduction

In C++, constructors are special member functions that initialize objects when they’re created. Among these, the default constructor plays a fundamental role in object-oriented programming, offering a simple way to set up an object with default values. Whether explicitly defined by the programmer or implicitly generated by the compiler, default constructors are essential for creating instances without predefined parameters.

Default Constructor in C++

In this article, we will learn about the concept of default constructors in C++, including their syntax, features, types, & examples.

Syntax of Default Constructors in C++

A default constructor in C++ is a type of constructor that is called automatically when an object is created without any arguments. It's very important and useful to know how to declare and utilize it within a class. Here's the basic syntax:

class ClassName {
public:
    ClassName() {
        // Constructor body: Initialization of the object
    }
};


In this example, ClassName is the name of the class, and ClassName() represents the default constructor. It doesn't take any parameters and is defined within the public section of the class. The body of the constructor can contain initialization code that sets up the initial state of an object.

Example of Default Constructor Syntax

Consider a class Car that needs to initialize certain properties when an object of Car is created:

class Car {
public:
    Car() {
        cout << "A new car has been created!" << endl;
        // Additional initialization can be added here.
    }
};


When you create an object of Car, the default constructor is called automatically, indicating that a new car has been created. This is useful for setting default values that helps in initial setup of tasks for new objects.

Features of Default Constructors in C++

  • Automatic Invocation: In case we do not pass any arguments to the newly created instance of a class, this will trigger the automatic invocation of default constructor. It guarantees that the object is properly initialized before it can be used.
     
  • No Parameters: Default constructors do not need external parameters. This helps in creating objects easily most importantly when there is no initial configuration.
     
  • Initialization Control: They are useful in ensuring that object members have their default values. These will help in avoiding un-initialized variables which could lead to unpredictable behavior of the program.
     
  • Overloading Capability: A class can have more than one constructors, including parameterized ones for facilitating versatile object initialization. The existence of a default constructor ensures that object has a simple way to be created using default values.
     
  • Flexibility in Object Creation: Even if explicit constructors are defined, having a default constructor helps in better flexibility. It enables creation of arrays of objects and declaration of objects without immediate initialization.
     

Let’s see an example to understand these : 

Let's consider a simple class Rectangle that uses a default constructor to initialize its dimensions:

  • C++

C++

class Rectangle {
public:
int width, height;

// Default constructor
Rectangle() : width(5), height(10) {
// Initial width and height are set by default.
}
};

int main() {
Rectangle myRect;
cout << "Width: " << myRect.width << ", Height: " << myRect.height << endl;
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

Width: 5, Height: 10


In this example, the Rectangle class initializes every new object with a width of 5 and a height of 10, thanks to the default constructor. When myRect is created, it automatically receives these default values, ensuring that the object is ready to use immediately after its creation.

Types of Default Constructors in C++

Default constructors in C++ can be classified based on how they are declared and defined. Let’s look at the different type of Constructors in C++ : 

  1. Implicitly-Declared Default Constructor
  2. Implicitly-Defined Default Constructor
  3. Deleted Implicitly-Declared Default Constructor
  4. Trivial Default Constructor
  5. Eligible Default Constructor

Now, lets understand them in detail -: 

1. Implicitly-Declared Default Constructor:

If a class does not have any user-defined constructors, the compiler will implicitly declare a default constructor for that class. This implicitly-declared default constructor has no parameters & an empty body. Here's an example:

class MyClass {
    int data;
};
int main() {
    MyClass obj;  // Implicitly-declared default constructor is called
    return 0;
}


In this example, MyClass does not have any user-defined constructors. When an object obj is created, the implicitly-declared default constructor is called to initialize the object.

The implicitly-declared default constructor will be deleted if any of the following conditions are true:

  • The class has a user-defined constructor with parameters.
     
  • The class has a non-static data member that does not have a default constructor.
     
  • The class has a base class or a virtual base class that does not have an accessible default constructor.

2. Implicitly-Defined Default Constructor

If a class has no user-defined constructors & no initializer list, the compiler will implicitly define a default constructor for that class. The implicitly-defined default constructor performs the following tasks:

  • Calls the default constructors of the class's direct base classes in the order they are declared.
     
  • Calls the default constructors of the class's non-static data members in the order they are declared.


Here's an example:

  • C++

C++

class Base {

public:

   Base() { std::cout << "Base default constructor" << std::endl; }

};

class MyClass : public Base {

   int data;

public:

   // No user-defined constructors

};

int main() {

   MyClass obj;  // Implicitly-defined default constructor is called

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

Output:

Base default constructor


In this example, MyClass inherits from the Base class & has no user-defined constructors. When an object obj is created, the implicitly-defined default constructor is called. It first calls the default constructor of the Base class & then initializes the data member of MyClass.

3. Deleted Implicitly-Declared Default Constructor

In certain situations, the compiler will implicitly declare the default constructor as deleted. When a default constructor is deleted, it means that it cannot be used to create objects of the class. The compiler will delete the implicitly-declared default constructor in the following scenarios:

  • The class has a user-defined constructor with parameters.
     
  • The class has a non-static data member that does not have a default constructor.
     
  • The class has a base class or a virtual base class that does not have an accessible default constructor.


Here's an example:

class Base {
public:
    Base(int x) { }
};
class MyClass : public Base {
public:
    // Implicitly-declared default constructor is deleted
};
int main() {
    MyClass obj;  // Compilation error: default constructor is deleted
    return 0;
}


In this example, the Base class has a parameterized constructor, which causes the implicitly-declared default constructor of MyClass to be deleted. When we try to create an object obj of MyClass, it results in a compilation error because the default constructor is deleted.

Note : To resolve this issue, we need to explicitly define a default constructor for MyClass or provide appropriate arguments to the base class constructor.

4. Trivial Default Constructor

A default constructor is considered trivial if it meets the following criteria:

  • It is implicitly-declared by the compiler.
     
  • The class has no virtual functions or virtual base classes.
     
  • All the direct base classes of the class have trivial default constructors.
     
  • All the non-static data members of the class have trivial default constructors.


A trivial default constructor performs no action and has no effect on the object's state. It is an optimization opportunity for the compiler.

Example of a class with a trivial default constructor:

class MyClass {
    int data;
};


In this example, MyClass has an implicitly-declared default constructor, no virtual functions or virtual base classes, and a non-static data member data with a trivial default constructor. Therefore, the default constructor of MyClass is considered trivial.

Note : Trivial default constructors are important for performance and optimization purposes. They allow objects to be created efficiently without any additional overhead.

5. Eligible Default Constructor

An eligible default constructor is a constructor that can be called without any arguments. It can be either a constructor with no parameters or a constructor where all parameters have default arguments.

Here are a few examples of eligible default constructors:

Example 1: Constructor with no parameters

class MyClass {
public:
    MyClass() {
        // Constructor body
    }
};

Example 2: Constructor with default arguments

class MyClass {
public:
    MyClass(int x = 0, std::string str = "") {
        // Constructor body
    }
};


In both examples, the constructors can be called without providing any arguments, making them eligible default constructors.

Example of using an eligible default constructor

MyClass obj1;          // Calls MyClass()
MyClass obj2(42);      // Calls MyClass(int x = 0, std::string str = "")
MyClass obj3(42, "Hello"); // Calls MyClass(int x = 0, std::string str = "")



In the above code, obj1 is created using the constructor with no parameters, while obj2 and obj3 are created using the constructor with default arguments.

Note : Eligible default constructors provide flexibility in object creation, allowing objects to be initialized with default values or with specific arguments as needed.

Examples of Default Constructors in C++

Here, we will see how default constructors operate within different scenarios to initialize objects seamlessly.

Example 1: Basic Initialization

Let's start with a basic example of a class with a default constructor that initializes member variables.

  • C++

C++

class Widget {
public:
int size;
string color;

// Default constructor
Widget() : size(10), color("blue") {
cout << "Widget created with size " << size << " and color " << color << endl;
}
};

int main() {
Widget myWidget;
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

Widget created with size 10 and color blue


In this example, when myWidget is created, its size is set to 10, and color to "blue". This demonstrates how a default constructor can set up an initial state for objects.

Example 2: Array of Objects

Default constructors are particularly useful when creating arrays of objects. Here’s how you can do it:

  • C++

C++

class Ball {
public:
double radius;

// Default constructor
Ball() : radius(5.0) {
cout << "Ball created with radius: " << radius << " units" << endl;
}
};

int main() {
Ball balls[3]; // Array of 3 Ball objects
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

Ball created with radius: 5 units
Ball created with radius: 5 units
Ball created with radius: 5 units


Each Ball object in the array is initialized using the default constructor, setting the radius to 5.0 units for each. This example highlights the constructor’s utility in managing arrays of objects.

Example 3: Dynamic Object Creation

When objects are dynamically created using pointers, default constructors ensure these objects are initialized immediately upon creation.

  • C++

C++

class Book {
public:
string title;

// Default constructor
Book() : title("Untitled") {
cout << "A new book titled '" << title << "' is created." << endl;
}
};

int main() {
Book *myBook = new Book; // Dynamically allocating a Book object
delete myBook; // Cleaning up the dynamically allocated Book
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

A new book titled 'Untitled' is created.


In this scenario, the Book titled "Untitled" is instantiated, showing how dynamically allocated objects are handled using default constructors.

Frequently Asked Questions

Why use a default constructor in C++?

A default constructor initializes an object without requiring arguments, setting up default values and ensuring the object is ready for use. It is essential for creating arrays or dynamically allocating objects without initial values.

Can a default constructor in C++ take arguments?

No, a default constructor cannot take arguments. It is specifically defined as a parameterless constructor, as it provides default initialization without needing input values.

Is it possible to disable the default constructor in C++?

Yes, by declaring the default constructor as = delete, you prevent automatic or manual default construction of objects, which is useful for enforcing specific initialization or preventing unintended instantiation.

In C++, when is the default constructor automatically called?

The default constructor is automatically called when an object is created without specified arguments, such as with arrays, dynamic allocation, or default member initialization in other classes.

Conclusion

In this article, we have learned Default Constructor in C++. The default constructor in C++ is a foundational tool for object initialization, ensuring that instances are created with reliable default values. By understanding when and how to use, disable, or customize the default constructor, developers can write more robust and efficient code. 

You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass