Constructor overloading in C++

                          Well hello guys, I am back again with a key concept of C++ programming language. This program is all about constructor overloading concept. Even if it is a very simple concept, one should have knowledge on it. Have a look at the concept explained below.
Concept:
                           Constructor is a special feature in C++ whose task is to initialize objects of its class. It is called constructor because it constructs the values of data members of the class. Constructors carry the same name of the class. When we initialize any object of the class, then we can pass values through the constructor during initialization only. Constructor overloading is that thing when in one class we use constructors with different no. of parameters. i.e. the when creating objects of the class, the number of arguments it will have, accordingly the required constructor will be active and others will remain inactive. We can have a short example here, whose sample output is as follows and so does the code.
Sample Output:

Program Code:

#include<iostream>
#include<conio.h>
using namespace std;

class complex
{
      float x, y;
      public:
             complex()    //0-argument constructor
             {
             }
             complex(float a)   //1-argument constructor
             {
                           x=y=a;
             }
             complex(float real,float imag)  //2-argument constructor
             {
                           x=real;
                           y=imag;
             }
             
             friend complex sum(complex, complex);
             friend void show(complex);
};
complex sum(complex c1, complex c2)
{
        complex c3;
        c3.x=c1.x+c2.x;
        c3.y=c1.y+c2.y;
        return(c3);
}
void show(complex c)
{
     cout<<c.x<<"+j"<<c.y<<"\n";
}
int main()
{
    complex A(2.7,3.5);
    complex B(1.6);
    complex C;
    
    C=sum(A,B);
    cout<<"Value of complex number A=";show(A);
    cout<<"Value of complex number B=";show(B);
    cout<<"Sum of A and B is C=";show(C);
    getch();
}

                          Well, as you can see, that here we have used three types of constructors that are 0-arg constructor,1-arg constructor, 2-arg constructor and for each type of constructor some different code is written. When ever any of the three constructors are called, it becomes active and its code is executed. I hope you have got the concept. This one is in the static input method, you can also make it dynamic by changing a few code.
                          That's it for now, thanks for viewing this content. If you get any query, use the comment box, otherwise contact me directly. Keep codung.. ;)

Comments

Popular posts from this blog

Non Restoring Division Algorithm Implementation in C

Bit Stuffing Code Implementation in Java

Hackerrank Modified Kaprekar Numbers Solution