Page Content

Tutorials

Default And Parameterized Constructors In C++ With Examples

Default and Parameterized Constructors In C++

Constructors in C++ are unique member functions of a class that are invoked automatically upon the creation of a new object of that class type. Initializing the data members of a class object is their main responsibility. In addition to sharing the same name as the class, constructors lack a return type not even void. Usually declared in a class’s public section, they enable object creation from any location where the class definition is accessible. As long as the constructors in a class have different kinds or numbers of parameters (their “signature”), they can be overloaded.

An description of parameterized and default constructors is provided below:

Default Constructors

You can call a default constructor without arguments.

Purpose: Create an object with default values. When an object has no initializers, the class’s default constructor initializes it.

Automatic Generation (Synthesized Default Constructor)

  • A class without constructors will have a default constructor defined by the compiler. This is a “synthesized default constructor”.
  • An in-class initializer is used if available; otherwise, the synthesized default constructor initializes each data member.
  • Built-in or compound types like arrays and pointers initialised by default in a block are undefined unless specifically initialised. Classes with such members should declare a default constructor or initialise them in-class to avoid undefined values.

Explicit Definition: The compiler will not build a default constructor if you define several class constructors. The default constructor must be specified explicitly.

Using = default: Even with alternative constructors, the C++ standard permits you to use = default after the parameter list in the declaration to inform the compiler to build the default constructor. It may be displayed on the definition outside of the class or inside the class body (inlined).

Code Example of a Default Constructor:

#include <iostream>
using namespace std;
class Line {
public:
    double length;
    // Default constructor explicitly defined
    Line() {
        length = 0.0; // Initializes length to a default value
        cout << "Object is being created by default constructor" << endl; 
    }
};
int main() {
    Line line; // Calls the default constructor 
    cout << "Length of line : " << line.length << endl;
    return 0;
}

Output

Object is being created by default constructor
Length of line : 0

In this example, the default constructor is invoked when a line is formed using Line line;. Because Line line(); would declare a function prototype instead, it is important to avoid brackets when declaring an object with the default constructor.

Parameterized Constructors

One or more arguments can be passed to parameterized constructors.

Purpose: When an object is created, they let you initialize its individual data members with distinct, predetermined values. This eliminates the requirement to invoke an additional initialization method following the creation of an object.

Initialization: The constructor receives arguments to set the initial values of the data elements of the object.

  • It is possible to convey arguments directly or implicitly.
    • Implicit call: integer int1(0, 100);
    • Explicit call: integer int1 = integer(0, 100);

A brief initialization syntax such as myclass ob = 99;, which the compiler translates to myclass ob = myclass(99);, can occasionally be used for constructors with a single parameter. A conversion from the type of the argument to the type of the class is implicitly created by a single-argument constructor, which is why this occurs.

Code Example of a Parameterized Constructor:

#include <iostream>
#include <string> // Required for std::string
class Book {
public:
    std::string title;
    std::string author;
    int year;
    // Parameterized constructor using an initializer list 
    Book(std::string t, std::string a, int y) : title(t), author(a), year(y) {
        std::cout << "Book object created with parameters: " << title << " by " << author << ", " << year << std::endl;
    }
};
int main() {
    // Implicit call to the parameterized constructor
    Book book1("The Lord of the Rings", "J.R.R. Tolkien", 1954); 
    // Explicit call (also valid but less common)
    Book book2 = Book("Dune", "Frank Herbert", 1965);
    return 0;
}

Output

Book object created with parameters: The Lord of the Rings by J.R.R. Tolkien, 1954
Book object created with parameters: Dune by Frank Herbert, 1965

Relationship between Default and Parameterized Constructors

  • Compiler synthesis of a default constructor is not guaranteed if a class contains at least one user-defined constructor (which suggests a parameterized constructor). This implies that you will get a compile-time error unless you additionally explicitly declare a default constructor if you define a parameterized constructor and then attempt to create an object without parameters.
  • If all of the arguments of a constructor are set to default values, the constructor can function as both a parameterized and a default constructor. In effect, a single definition is transformed into a “overloaded” constructor set.

You can also read What Is Mean By Data Hiding And Encapsulation In C++?

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index