×

Constructor Overloading in C++

A Constructor is a class member function that is used to initialize the class's objects. Constructors have no return type and are called automatically when an object is formed.

Constructor Characteristics

  • Constructors don't have a return type.
  • When the object is created, it is immediately called. It is always placed in the class's public scope.
  • If no constructor is specified, the default constructor is used, which sets the value of the data member to zero.
  • The name of the function Object ( ) { [native code] } is case-sensitive.
  • A function Object ( ) { [native code] } is not inherited by default.

Types of Constructor

Default Constructor: It's used to assign a value to data members. When an object is created, the default function Object () { [native code] } is invoked.

Example:

#include < iostream >  
#include < bits/tsdc++.h >
#include < stdlib >
using namespace std ;  
class construct  // create a class construct  
{  
public:  
    int x , y ; // initialise two data members   
    construct ( ) // this is how default constructor is created   
    {  
        // We can also assign both values to zero   
        x = 10 ; // intialise x with some value   
        y = 20 ; // initialise y with some value  
    }  
} ;  
int main ( )  
{     
    construct z ; // creating an object of construct calls defualt constructor  
    cout << "x:" << z.x << endl ;
        << "y:" << z.y ; // print x and y
    return 1 ;  
}  

OUTPUT:

X: 10
Y:20
……..
Process executed in 0.11 seconds
Press any key to continue.

Explanation:

In the program above in C ++, we created a builder class and announced the default builder. In the main work we started the builder thing by z.

Parameterized Constructor is non-parameterized function Object() { [native code] } has function Object() { [native code] } arguments, and the value supplied in the argument is initialised to its data members. Parameterized constructors are utilised in function Object() { [native code] } overloading.

Example:

#include < iostream >  
#include < bits/stdc++.h >
#include < stdlib >
using namespace std ;  
class Point // create point class  
    {  
private :  
int a , b ; // the two data members of class Point  
public :  
Point ( int a1 , int b1 ) // create paramterised Constructor and initialise data member  
    {  
        a = a1 ; // a1 is now intialised to a  
        b = b1 ; // a1 is now intialised to b  
    }  
intgetA ( )  
    {  
return a ; // to get the value of a  
    }  
intgetB ( )  
    {  
return b ; // to get the value of b  
    }  
} ;  
int main ( )  
{  
Point pt1 ( 10 , 15 ) ; // created object for paramterised constructor  
cout << "pt1.a = " << pt1.getA ( ) << " , pt1.b = " << pt1.getB ( ) ; // print a and b 
return 0 ;  
}

OUTPUT:

Pt1.a = 10 ,pt1.b = 15
……………………………..
Process executed in 0.11 seconds
Press any key to continue.

Explanation:

Make a class point out of the two data elements a and b. A parameterized constructor is formed using the parameters a1 and b1, and the values of a and b are assigned using a1 and b1. We build a parameterized constructor using the values in the main function (10, 15). The values of the data members are obtained using the getter functions.

Constructor Overloading

Similarly to the idea of function overloading, constructor overloading is used. Constructor overloading occurs when we overload a function Object with more than one purpose. The conditions for overloading a function Object are to change the number or type of parameters.

Example:

// C++ program to demonstrate constructor overloading  
#include <iostream>  
using namespace std;  
class People { // create people class  
private:  
int Age; // data member  
public:  
    // 1. Constructor with no arguments  
People ()  
    {  
Age = 10; // when object is created the age will be 20  
    }  
    // 2. Constructor with an argument  
People (int a)  
{ // when parameterised Constructor is called with a value the  
        // age passed will be initialised  
Age = a;  
    }  
intgetage()  
{ // getter to return the age  
return Age;  
    }  
};  
int main()  
{  
People person1 , person2 ( 20 ) ; // called the object of people class in differnt way  
cout<< "Person1 Age = " << person1.getage() <<endl;  
cout<< "Person2 Age = " << person2.getage() <<endl;  
return 0;  
}  

OUTPUT:

Person1 Age = 10
Person2 Age = 20
………………………..
Process executed in 0.11 seconds
Press any key to continue.

Explanation:

In the preceding program, we established a People class with one data member (Age). We've overloaded the second by passing it one argument and parameterzing it. As a result, when the object person1 age is printed, it returns the default value of 20, however person2 age returns 45 since it was supplied by the object to the parameterized constructor.


Related Topics

Compile Time Polymorphism in C++

What is Polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. One application of polymorphism in...

4 minutes read.

C++ Recursion Function

A programming method called recursion that uses a function to call itself to address lesser problems. The Fibonacci sequence, factorial computation, and tree traversal are just a few of the...

4 minutes read.

Destructor

Let’s discover the C++ destructor, virtual and pure virtual destructors, and when destructors are invoked and their rules in this lesson. Destructors : A member function that destroys an object is known as...

5 minutes read.

C++ Program to find the largest number formed from an array

Given an array, write a program to find the largest number that will be formed from the elements of the array. Arrangement should be done in such a way that...

4 minutes read.

Static keyword in C++ vs Java

Both in C++ and Java, the static keyword is employed for essentially the same function. But there are some variations. The static keyword's similarities and differences between C++ and Java...

3 minutes read.

Remove duplicates from sorted array in C++

Remove duplicates from the sorted array in C++. This same process, due to a sorted array, is to erase the redundant components from the array. Examples: Input  : arr[] = {2, 2, 2,...

4 minutes read.

Nullptr in C++

What is Nullptr in C++? A null pointer value is represented by the term nullptr. Use a null pointer value to indicate that a native pointer type, inner pointer, or object...

3 minutes read.

Decimal to Octal in C++

We must create a software that converts a decimal number into an equal octal number given a decimal number as input i.e. convert a number having a base value of...

3 minutes read.

Is it fine to write void main() or main() in C/C++?

In C programming language: The default function return type in the C programming language is "int," which implies that main() will always return an integer value. In C, the void main()...

3 minutes read.

Vector in C++

Vector in C++ In today’s article, we will be learning all the things about vector in C++ and how vector is different form an array in C++. So basically, vector is very...

3 minutes read.

Vector resize() in C++

Vector resize() in C++ Vectors are called dynamic arrays and can automatically adjust their size when a component is added or deleted. This container is used for storage. The function modifies the...

3 minutes read.

Type conversion in C++

Type conversion is the process of changing the type of variables in a program. The ultimate goal of type conversions is to allow variables of a single data type operate with...

7 minutes read.

Substring in C++

A substring is a function in c++ that is imported from the string library. An element of a string is called a substring. A substring contains two parameters length and...

2 minutes read.

Default Constructor

C++ Default Constructor A default constructor is such constructor which does not take any parameter. A constructor initializes the data member when a class object created. If a programmer does not create any...

2 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers...

4 minutes read.

Hybrid Inheritance

C++ Hybrid Inheritance When more than one type of inheritance is combined in single inheritance is called as hybrid inheritance. C++ Hybrid Inheritance Example #include<iostream>   using namespace std;   class Student{       protected:           int rollno;       public:           void getRoll(int a){               rollno=a;           }           void putRoll(void){               cout <<"Roll No: "<< rollno<<endl;           }   };   class Test : public Student{       protected:           float subject1, subject2;       public:           void getMarks(float x, float y){               subject1=x;               subject2=y;           }           void putMarks(void){               cout<< "Marks gain: "<<endl <<"Subject1 =  "<<subject1<<endl<<"Subject2 = "<<subject2 <<endl;           }   };   class Sport{       protected:           float score;       public:           void getScore(float s){               score=s;           }           void putScore(void){               cout<<"Sports score: "<<score<<endl;           }   };   class Result : public Test, public Sport{       float total;       public:           void display(void);   };   void Result:: display(void){       total=subject1+subject2+score;       putRoll();       putMarks();       putScore();       cout<<"Total Score: "<<total<<endl;   }   int main(){       Result stu;       stu.getRoll(10);       stu.getMarks(40,50);       stu.getScore(60);       stu.display();       return 0;   } Output: Roll No: 10 Marks gain: Subject1 = 40 Subject2 = 50 Sports score: 60 Total...

1 minute read.

fscanf() Function in the C++

In the C++ programming language, the fscanf() method can be used to read data from a file stream. Syntax: The syntax for the fscanf() function in the C++ programming language is as...

3 minutes read.

C++ History

C++ is a middle-level programming language developed in 1980s by Bjarne Stroustrup at Bel Labs. C ++ development initially started in 1979, four years before its launch. It is started with...

1 minute read.

Armstrong Number using Do-While Loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

4 minutes read.