Back to C++
2025-12-296 min read

Default constructor (C++)

Learn Default constructor (C++) step by step with clear examples and exercises.

Why This Matters

Understanding default constructors is crucial in C++ programming as it allows you to create objects without providing explicit initialization values for all member variables. This knowledge is essential for acing exams, interviews, and real-world coding scenarios where constructors play a vital role. Default constructors help in creating objects with default values when no specific initializers are provided, making the code more flexible and easier to manage.

Prerequisites

Before diving into the intricacies of default constructors, it's important that you have a strong foundation in C++ basics: variables, data types, operators, classes, objects, constructors, destructors, and inheritance. If you're not familiar with these concepts, we recommend reviewing them before proceeding.

Core Concept

A default constructor is a special member function of a class that gets called automatically when an object is created without any arguments being passed. Its primary purpose is to initialize the data members of the class with default values if they are not explicitly initialized. In C++, if you don't define any constructors for a class, the compiler generates a default constructor for you. This generated default constructor initializes all member variables with their default values (zero for numeric types and nullptr for pointers). However, you can also write your own default constructor to initialize the data members as per your requirements.

Syntax

The syntax for defining a default constructor is simple:

class_name();

For example, consider the following class definition with two member variables m_x and m_y:

class Point {
private:
int m_x;
int m_y;
public:
// Default constructor
Point();
};

To create an object of the Point class without passing any arguments, you can call the default constructor:

Point p;

Initializing Data Members

If you want to initialize the data members with specific values instead of their default values, you can write a custom default constructor. Here's an example:

class Point {
private:
int m_x;
int m_y;
public:
// Default constructor
Point() : m_x(0), m_y(0) {}
};

In this example, we've defined a custom default constructor that initializes m_x and m_y to 0. Now when you create an object of the Point class:

Point p;

The data members will be initialized to 0 instead of their default values.

Initialization Lists

Initialization lists provide a more flexible way to initialize member variables in constructors, especially when dealing with classes that have base classes or complex member objects. Here's an example:

class Base {
public:
int m_base;
};

class Derived : public Base {
private:
int m_derived;
public:
// Default constructor using initialization list
Derived() : Base(), m_derived(0) {}
};

In this example, the base class Base is initialized first (with its default constructor), and then m_derived is initialized with 0. This ensures that the base class subobject is properly initialized before the member object.

Worked Example

Let's look at into a more complex example that demonstrates how default constructors work in C++. We'll create a Student class with member variables representing the student's name, age, and grade point average (GPA).

#include <iostream>
using namespace std;

class Student {
private:
string m_name;
int m_age;
float m_gpa;
public:
// Default constructor
Student() : m_name(""), m_age(0), m_gpa(0.0) {}

void setName(string name) {
m_name = name;
}

void setAge(int age) {
m_age = age;
}

void setGPA(float gpa) {
m_gpa = gpa;
}

void printDetails() {
cout << "Name: " << m_name << ", Age: " << m_age << ", GPA: " << m_gpa << endl;
}
};

int main() {
// Creating a Student object using the default constructor
Student s1;
s1.printDetails(); // Outputs Name: , Age: 0, GPA: 0.0

// Setting values for s1
s1.setName("John Doe");
s1.setAge(23);
s1.setGPA(3.5);
s1.printDetails(); // Outputs Name: John Doe, Age: 23, GPA: 3.5

// Creating another Student object with custom values
Student s2("Jane Smith", 24, 3.8);
s2.printDetails(); // Outputs Name: Jane Smith, Age: 24, GPA: 3.8

return 0;
}

This example demonstrates that the default constructor initializes all member variables to their default values (an empty string for m_name, 0 for m_age, and 0.0 for m_gpa). After setting the values, we can see that the printDetails() function correctly outputs the updated information for both objects.

Common Mistakes

  1. Forgetting to define a default constructor: If you don't define any constructors for your class and the class has no user-defined constructors that take arguments, the compiler generates a default constructor for you. However, if you define other constructors that take arguments, the compiler won't generate a default constructor anymore. In such cases, you must explicitly define a default constructor.
  1. Not initializing data members in custom constructors: If you write your own constructors and forget to initialize the data members, they will remain uninitialized. This can lead to undefined behavior when you try to use the object. Always make sure to initialize all data members in your constructors.
  1. Misunderstanding the role of default constructors: Default constructors are not always used to create objects with default values. They are primarily used when you want to create an object without passing any arguments. If you need to create objects with specific values, use constructor overloading or provide initialization lists in your constructors.
  1. Incorrectly initializing data members: When using initialization lists, ensure that the order of initialization matches the declaration order of data members. Also, be aware that base class subobjects are initialized before member objects and data members.

Practice Questions

  1. Write a custom default constructor for the Point class that initializes m_x and m_y to 10.
class Point {
private:
int m_x;
int m_y;
public:
// Default constructor
Point() : m_x(10), m_y(10) {}
};
  1. Create a class Square with a member variable representing the side length. Define a default constructor that initializes the side length to 1.
class Square {
private:
int m_side;
public:
// Default constructor
Square() : m_side(1) {}
};
  1. Write a program that creates an array of 5 Rectangle objects, initializing each one with different widths and heights.
#include <iostream>
using namespace std;

class Rectangle {
private:
int m_width;
int m_height;
public:
// Default constructor
Rectangle() : m_width(0), m_height(0) {}

void setWidth(int width) {
m_width = width;
}

void setHeight(int height) {
m_height = height;
}

int getArea() {
return m_width * m_height;
}
};

int main() {
Rectangle rectangles[5];

// Initializing each rectangle with different widths and heights
for (int i = 0; i < 5; ++i) {
rectangles[i].setWidth(i * 2 + 1);
rectangles[i].setHeight(i * 2 + 1);
}

// Printing the area of each rectangle
for (int i = 0; i < 5; ++i) {
cout << "Rectangle " << i + 1 << " area: " << rectangles[i].getArea() << endl;
}

return 0;
}

This program creates an array of Rectangle objects and initializes each one with different widths and heights. It then calculates and prints the area of each rectangle.

FAQ

Q: What happens if I don't define any constructors for my class?

A: If you don't define any constructors for your class and the class has no user-defined constructors that take arguments, the compiler generates a default constructor for you. However, if you define other constructors that take arguments, the compiler won't generate a default constructor anymore. In such cases, you must explicitly define a default constructor.

Q: Can I have multiple default constructors in a class?

A: No, you cannot have multiple default constructors in a class. If you define any constructor (including a default constructor), the compiler won't generate another one. However, you can use constructor overloading to create multiple constructors that take different numbers or types of arguments.

Q: What is the difference between a default constructor and a parameterized constructor?

A: A default constructor is a constructor without any parameters, while a parameterized constructor has one or more parameters. The default constructor initializes the data members with their default values if they are not explicitly initialized, whereas a parameterized constructor initializes the data members using the arguments passed to it.

Q: How do I initialize base class subobjects in a custom constructor?

A: To initialize base class subobjects in a custom constructor, you can use an initialization list. The initialization list appears immediately after the colon (:) following the base class name in the constructor declaration. For example:

class Base {
public:
int m_base;
};

class Derived : public Base {
public:
int m_derived;

Derived(int b, int d) : Base(b), m_derived(d) {}
};

In this example, the base class Base is initialized first (with the provided argument), and then m_derived is initialized with the second argument. This ensures that the base class subobject is properly initialized before the member object.

Default constructor (C++) | C++ | XQA Learn