VOOZH about

URL: https://www.geeksforgeeks.org/cpp/default-constructors-in-cpp/

⇱ Default Constructors in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Default Constructors in C++

Last Updated : 20 Dec, 2025

In C++, a constructor is a special member function that is automatically called when an object of the class is created.

  • A default constructor is the one that takes no arguments. It is either defined explicitly by the programmer or implicitly generated by the compiler.
  • If you do not explicitly define any constructor in your class, the C++ compiler automatically provides a default constructor.

Example 1: No User Defined Constructor

In the below class, a default constructor will be generated by the compiler at compile time.

Example 2: Explicitly Defined Default Constructor

In this example, a constructor with no parameters is explicitly defined. Since a constructor already exists, the compiler will not generate one.

Objects of this class can be created without arguments.

Example 3: Default Constructor with Initialization

You can also initialize class members inside the default constructor.

Explanation:

  • The default constructor initializes the data member x.
  • It runs automatically at object creation time.
  • Useful for setting initial default values.

Complete Example


Output
Default constructor called
Name: Unknown, Roll: -1

Explanation

  • s1 is created without arguments.
  • The default constructor initializes name and roll.
  • display() prints the initialized values.

Use Cases of Default Constructor:

  • Creating arrays or vectors of objects
  • Needed when using STL containers (like vector<Class>)
  • Used when objects need to be initialized to default values
  • Required in generic programming and templates
Comment
Article Tags:
Article Tags: