×

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

ATM machine program in C++ using functions

Automated Teller Machines (ATMs) carry out daily financial transactions. They are straightforward and simple, allowing customers to complete self-service transactions quickly. ATMs can then be used to withdraw cash, deposit...

3 minutes read.

Memset in C++

Memset () is a function in the C++ programming language that fills memory blocks. The value of "ch" is first converted to an unsigned character. In this case, "ch" denotes the...

3 minutes read.

Structure Vs Class in C++

The structure in C++ is similar to that of a class, with a few exceptions. Both the structure and the stage, the most important thing is safety. The property is...

4 minutes read.

C++ this pointer

'this' is a pointer that points to the object for which this function was called. The 'this' pointer holds the memory address of the current object. The 'this' pointer is implicitly passed to...

2 minutes read.

Containership in C++

In C++, it is possible to create an object in one class into another class, and that object is a member of another class. This relationship is known as a...

4 minutes read.

C++ int into String

Data type conversion is a standard editing process. You may need to convert variable from one type of data to another in a variety of situations. There are two ways...

5 minutes read.

C++ Fork

A new process known as a "child process" is created with the fork system function and runs concurrently with the process that invoked fork() (parent process). Both processes will carry...

4 minutes read.

C++ Expressions

C ++ equations are made up of operators, constants and variables arranged according to language rules. It may also include function calls that give results. To calculate the value, the...

4 minutes read.

C++ Comments

Comment/Remark A Comment or a Remark is text that is ignored by the compiler yet is beneficial to programmers. Code is usually annotated with comments for future reference. They are treated...

3 minutes read.

How to Reverse a String in C++ using For Loop

For Loop: We may loop through a certain section of C++ code repeatedly using the for loop. A for loop is carried out if the test expression yields a true result. The...

4 minutes read.

Singleton Design Pattern in C++

Singleton is similar to the global variable. Singleton helps to have only one object of its kind and provides only single access. One of the key features of the singleton...

2 minutes read.

Binary to Decimal in C++

We must create a software to convert a binary number into an equivalent decimal value given a binary number as input. Example: // C++ program to convert binary to decimal #include < iostream...

3 minutes read.

Dynamic Binding in C++

The notion of dynamic binding solved the challenges associated with static binding. Static binding refers to bindings that can be resolved by the compiler at runtime. All storage, stationary, and...

3 minutes read.

C++ Writing to file

In file handling, write() function is used to write data into the file. The write() uses ofstream or fstream library to write into the file. Syntax file-stream-class   file-stream-object;   file-stream-object.write((char *)&var , sizeof (var)); The write() takes two arguments. The first argument is the address of variable var...

2 minutes read.

Lexicographically Next Permutation in C++

In this tutorial, we'll look at how to use C++ to generate the lexicographically next permutation of a string. The lexicographically next permutation is the larger permutation. "ACB," for example,...

3 minutes read.

Multilevel Inheritance

C++ Multilevel Inheritance Multilevel inheritance is such an inheritance in which a derived class is created from another derived class. C++ Multilevel Inheritance Example In this example, a base class Student is inherited in...

2 minutes 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.

Method overriding in C++

What is method overriding? Using the same function in derived class as their base class is referred to as function/method overriding in c++. Method overriding is an example of polymorphism. With...

2 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.

Difference between Two Sets in C++

The distinction between the two sets is made up of the components that are present in the first set but absent from the second set. The function consistently duplicates the...

3 minutes read.