fbpx

The Role of Constructor Overloading in Object-Oriented Programming

Constructor overloading


INTRODUCTION

Constructor overloading is a concept in object-oriented programming where a class can have multiple constructors with the same name (as the class itself) but differing in the number or types of parameters. This flexibility allows developers to create objects in various ways, depending on the arguments passed during object instantiation.

For example, a class can have a default constructor and parameterized constructors to initialize objects with different sets of values. The compiler automatically selects the appropriate constructor based on the arguments, simplifying object creation and improving code clarity.

Constructor overloading is a versatile feature that enhances code modularity and flexibility, ensuring efficient initialization of objects in diverse scenarios.

Constructor overloading occurs when multiple constructors in a class share the same name as the class but differ in the number or types of their arguments.

The constructor to be invoked is determined by the arguments passed while creating an object. These arguments guide the compiler in selecting the appropriate constructor.

#include<iostream>

using namespace std;                                  

class areaOfRectangle

{

public

float area;

areaOfRectangle(int a)

{

area=0;

}

areaOfRectangle(int a ,int b)

{

area=a*b;

}

    void disp()

    {

        cout<< area<< endl;

    }

 

};

int main()

{

    areaOfRectangle o;

    areaOfRectangle o2( 10, 20);

      

    o.disp();

    o2.disp();

    return 1;

}

Functions that cannot be overloaded.

Functions with same name and with different return type cannot be overloaded.

#include<iostream>

int display() {

return 10;

}

char display() {

return ‘a’;

}

 

int main()

{

char x = display();

getchar();

return 0;

}

                                                                                                  

The function with same name and same no of arguments  and one with static cannot be overridden.

#include<iostream>

class Test1 {

static void fun(int i) {}

void fun(int i) {}

};

 

int main()

{

Test1 t;

getchar();

return 0;

}

Function overloading cannot be done in this case also.

int fun(int *ptr);

int fun(int ptr[]); // redeclaration of fun(int *ptr)

Function overloading cannot be done in this case also:

void h(int ());

void h(int (*)()); // redeclaration of h(int())