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++
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++ :
- Implicitly-Declared Default Constructor
- Implicitly-Defined Default Constructor
- Deleted Implicitly-Declared Default Constructor
- Trivial Default Constructor
- 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++
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++
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++
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++
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 DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.