0
0
C++programming~5 mins

Default constructor in C++

Choose your learning style9 modes available
Introduction

A default constructor helps create an object with default values automatically.

When you want to create an object without giving initial values.
When you want to set default values for object properties.
When you want to create multiple objects quickly with the same starting state.
Syntax
C++
class ClassName {
public:
    ClassName() {
        // code to set default values
    }
};

The default constructor has no parameters.

If you don't write one, C++ creates a default constructor automatically if no other constructors exist.

Examples
This default constructor sets speed to 0 and color to red when a Car object is created.
C++
class Car {
public:
    Car() {
        speed = 0;
        color = "red";
    }
private:
    int speed;
    std::string color;
};
This uses the compiler-generated default constructor without custom code.
C++
class Box {
public:
    Box() = default;
};
Sample Program

This program creates a Person object using the default constructor. It sets name to "Unknown" and age to 0, then prints these values.

C++
#include <iostream>
#include <string>

class Person {
public:
    Person() {
        name = "Unknown";
        age = 0;
    }
    void display() {
        std::cout << "Name: " << name << ", Age: " << age << std::endl;
    }
private:
    std::string name;
    int age;
};

int main() {
    Person p;
    p.display();
    return 0;
}
OutputSuccess
Important Notes

If you define any constructor with parameters, C++ will not create a default constructor automatically.

You can use = default; to ask the compiler to create a default constructor for you.

Summary

A default constructor creates objects with default values.

It has no parameters and can be written by you or generated by the compiler.

Use it to make object creation simple and consistent.