Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
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.
Implicitly-Declared Default Constructor:
5.2.
Implicitly-Defined Default Constructor
5.3.
C++
5.4.
Deleted Implicitly-Declared Default Constructor
5.5.
Trivial Default Constructor
5.6.
Eligible Default Constructor
5.7.
Example 1: Constructor with no parameters
5.8.
Example 2: Constructor with default arguments
5.9.
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.
What happens if I don't define a default constructor in my class?
7.2.
Can a default constructor be private, and if so, why would that be useful?
7.3.
Is it possible to delete a default constructor, and what would be the reason?
8.
Conclusion
Last Updated: Jun 11, 2024
Easy

Default Constructor in C++

Author Gaurav Gandhi
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

A constructor is a special member function in C++ that is automatically called when an object of a class is created. Its main objective is to initialize the object's data members & set the object to a valid state. The default constructor is a type of constructor that doesn't take any arguments. 

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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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;
}

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: If no constructor is explicitly defined for a class, the compiler implicitly declares a default constructor. This constructor has no parameters & an empty body.
     
  2. Implicitly-Defined Default Constructor: If a class has no user-defined constructors & no initializer list, the compiler will implicitly define a default constructor. This constructor will call the default constructors of the class's non-static data members & base classes.
     
  3. Deleted Implicitly-Declared Default Constructor: In certain situations, such as when a class has a non-default constructor or a virtual base class, the compiler will implicitly declare the default constructor as deleted. This means that the default constructor cannot be used to create objects of that class.
     
  4. Trivial Default Constructor: A default constructor is considered trivial if it is implicitly-declared, belongs to a class with no virtual functions or virtual base classes, & all its direct base classes & non-static data members have trivial default constructors.
     
  5. Eligible Default Constructor: An eligible default constructor is a constructor that can be called without any arguments. It can be a constructor with no parameters or a constructor where all parameters have default arguments.

Now, lets understand them in detail -: 

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.

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;

}

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.

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.

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.

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;
}

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;
}

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;
}

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

What happens if I don't define a default constructor in my class?

If you don't define a default constructor, the C++ compiler automatically generates one for you, provided your class does not have any constructors that take parameters. This constructor does minimal work, usually just initializing member objects which themselves have constructors.

Can a default constructor be private, and if so, why would that be useful?

Yes, a default constructor can be private. This is often used in the Singleton design pattern where the constructor is made private to prevent other classes from creating an instance of the Singleton class, ensuring that only one instance of the class exists throughout the program.

Is it possible to delete a default constructor, and what would be the reason?

Yes, you can explicitly delete a default constructor using = delete;. This is useful when you want to prevent the creation of an object without specific parameters, ensuring that objects are always created with certain initial values or through specific methods.

Conclusion

In this article, we have learned about default constructors in C++. We discussed their syntax, features, and types, which includes implicitly-declared, implicitly-defined, deleted, trivial, and eligible default constructors. We also looked at several examples to understand how default constructors are used to initialize objects with default or specific values. Finally, we understood how default constructors play a crucial role in object initialization and provide flexibility in object creation.

You can refer to our guided paths on the Coding Ninjas. 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