Programmingoneonone is known for sharing best programming knowledge.

Parameterized constructor in c++ programming

in this post, you will learn about parameterized constructor in c++ programming and learn how to declare and define a parameterized constructor in c++ programming. 


parameterized constructor in c++ programming, learn c++ programming
learn c++ programming 

Parameterized constructor:

the constructor in which we give the parameter is called a parameterized constructor.

Example:
              class test
              {
                   int x,y;

                public:
                        test(int a, int b)
                        {
                            x=a;
                            y=b;
                        }
             };

How to give the value to the constructor:

to give the value to the constructor we need to pass the value at the time of creating an object of the class. 

Example:
in the above example, we pass the two value a and b in the parameterized constructor. so to give the value to the constructor we need to pass the value at the time of creating an object. 

syntext:
             <class-name> <class-object>(parameters);

Example:
              class obj(10,20);


Example program using parameterized constructor in class:

   #include <iostream>

   class your
   {
         int x,y,z;

         public:

           your(int a, int b) //parameterized constructor and the same name as like class.
           {
              x=a;
              y=b;
              z=x+y;

              std::cout<<"\n addition of x and y is: "<<z;
           }
   };

   int main()
   {
       your obj(10,20); //after creating an object the constructor is automatically called.

       return 0;
   }

Note: in above example, we create a class name your and in class, we create a parameterized constructor and pass the two values a and b. and pass the value in the constructor at the time of creating the object. 

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

No comments:

Post a Comment