c-plus-plus
  1. c-plus-plus-constructor-overloading

C++ Programs: Constructor Overloading

Constructor overloading in C++ allows a class to have multiple constructors with different parameters to create objects with different initial values. This is part of the concept of Polymorphism in C++, allowing a single function name to have multiple definitions.

Syntax

class MyClass {
    public:
        //default constructor
        MyClass(){
            //code
        }
        //parameterized constructor
        MyClass(int var1, int var2){
            //code
        }
}

In the above example, we have defined two constructors: a default constructor and a parameterized constructor that takes two integers as input.

Example

#include <iostream>
using namespace std;

class MyClass {
    int var1;
    int var2;

    public:
        // default constructor
        MyClass(){
            var1 = 0;
            var2 = 0;
        }

        // parameterized constructor
        MyClass(int x, int y){
            var1 = x;
            var2 = y;
        }

        void print() {
            cout << "var1 = " << var1 << endl;
            cout << "var2 = " << var2 << endl;
        }
};

int main() {
    MyClass obj1; //default constructor
    obj1.print();

    MyClass obj2(10, 20); //parameterized constructor
    obj2.print();

    return 0;
}

Output

var1 = 0
var2 = 0

var1 = 10
var2 = 20

Explanation

In the above example, we have defined a class called "MyClass" with two constructors: a default constructor and a parameterized constructor. The default constructor initializes the variables var1 and var2 to 0, while the parameterized constructor takes two integers as input and initializes the variables var1 and var2 to those values.

In the main function, we have created two objects of the class: obj1 using the default constructor and obj2 using the parameterized constructor. We then call the member function "print" to print the values of the variables in each object.

Use

Constructor overloading is useful when we want to create objects with different initial values. We can have a default constructor for initializing variables to default values and parameterized constructor for initializing variables to specific values.

Important Points

  • Constructor overloading allows a class to have multiple constructors with different parameter lists.
  • The constructors are differentiated based on the number, type, and order of their arguments.
  • If a constructor with a specific parameter list is not defined, the default constructor will be called.

Summary

In summary, constructor overloading in C++ allows a class to have multiple constructors with different parameter lists. This helps to create objects with different initial values and is useful in Polymorphism. The constructors are differentiated based on their parameter lists, and if a constructor with a specific parameter list is not defined, the default constructor will be called.

Published on: