Friday, March 1, 2019

constructor overloading in c++ programming

In this post, you will learn about constructor overloading in c++ programming and learn why we use constructor overloading in programming. 


constructor overloading in c++ programming, learn c++ programming
learn c++ programming

constructor overloading:

like function overloading, we also overload the constructor. we can use the one or more constructor in our program with different parameters. and this feature is called constructor overloading. 

Example:
              class test
              {
                  public:

                      test();               //constructor with no parameter
                      test(int x);       // constructor with one parameter
                      test(int x, int y); // constructor with two parameter. 

              };


Example programe using constructor overloading:

#include <iostream>

class test
{
   int a,b;

 public:
           
    test()     //define first costructor with no parameter
    {
      a=0;
      b=0;
      std::cout<<"\n value of a and b is: "<<a<< b;
    }
           
    test(int x) //define second constructor with one parameter
    {
       a=x;
       b=x;
       std::cout<<"\n value of a and b is: "<<a<< b;
    }       
    test(int x, int y) //define third constructor with second parameter
    {
        a=x;
        b=y;
        std::cout<<"\n value of a and b is "<<a<< b;
    }

};

 int main()
{
    test t1; //called first constructor 
    test t2(10); //called second constructor
    test t3(10,20); //called third constructor
       
    return 0;
}


learn c++ programming,programming tutorials
learn c++ programming
   feel free to use this code. just copy this code and paste in your compiler or editor and use it. 

"Please share this knowledge as much possible as you can and also comment me your queries and questions related to this topic. I will really grateful to help you."

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete