C++ allows us to use a default constructor and a parameterized constructor in the same class. One constructor does not accept any arguments and the other constructor accepts arguments.

Hence, it is possible to have more than one constructor with the same name but different argument list.

Depending on the manner in which the object is initialized, the corresponding constructor is invoked.

Simple Example Program For Constructor Overloading In C++ program

#include<iostream>
using namespace std;
class MyPack{ 
int a; public: MyPack(){ 
cout<<"Default constructor called"<<endl; 
a=10; } 
MyPack(int x){ 
cout<<"One - argument parameterized constructor called"<<endl; 
a = x; } 
void print(){ 
cout<<"The value of a is :"<<a<<endl;
} }; 
int main(){ 
MyPack s1(8); //Way to call an overloaded constructor 
MyPack s2;
s1.print(); 
s2.print();
return 0;
 }

Output:-One – argument parameterized constructor called
Default constructor called
The value of a is :8
The value of a is :10

Explanation of the program

In this program, the class MyPack has 2 constructors – one is default constructor and the other is a parameterized constructor which accepts one argument.

While object s1 and s2 are initialized, s1 passes an argument whereas s2 does not pass any argument.

Hence when s1 is created, the parameterized constructor is invoked. When s2 is created, the default constructor is invoked.

This article is written by our awesome writer
Comments to: Constructor Overloading In C++ with a simple example

Your email address will not be published. Required fields are marked *

Attach images - Only PNG, JPG, JPEG and GIF are supported.

New Dark Mode Is Here

Sign In to access the new Dark Mode reading option.

Join our Newsletter

Get our monthly recap with the latest news, articles and resources.

By subscribing you agree to our Privacy Policy.

Latest Articles

Explore Tutorials By Categories

About

Codeverb is simply an all in one interactive learning portal, we regularly add new topics and keep improving the existing ones, if you have any suggestions, questions, bugs issue or any other queries you can simply reach us via the contact page

Login

Welcome to Codeverb

Ready to learn something new?
Join Codeverb!

Read Smart, Save Time
  •  
    Strength indicator
  •  
  •  
    Log In | Lost Password