Wednesday, February 6, 2019

constructor in c++ programming

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


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

constructor:

a constructor is a specific type of data. which is a subset of class.

Example: 
                class test
                {
                     int x,y;

                  public:

                       test() // constructor 
                       {
                              a=0;
                              b=0;
                        }
                 };

Rules for declaring constructor:

  • a constructor is always defined in the public scope.
  • it does not have any return type. it's always void type. 
  • it's automatically invoked.
  • it has the same name as a class(as you see in the above example).
  • when we create an object of the class immediately it gives the value to object.
  • it's not inherited.
  • it's not virtual.

How to define a constructor in class:

syntext:
            class <class-name> // class
           {
                 public:

                       <class-name>(parameters) //constructor 
                       {
                                    //code for execution;
                       }
                    
            };

Example:
               class your
                {

                   public:
                          your()
                          {
                             //code for execution;
                          }
                };
Note: to call the constructor we just need to declare the object of class. 



An example program using a constructor in a class.


      #include <iostream>

      class your 
      {
              int x,y,z;

              public:

                    //constructore which has same name as class.
                   your() 
                   {
                        x=10;
                        y=20;  //code for execution 
                        z=x+y;
                        std::cout<<"\n z ="<<z;
                   }
      };

      int main()
      {

          your obj; 
    /*when we create the class's object. the constructor is automatically called           and it automatically gives the value to the variables. */                

          return 0;

      }

Note: in the above example here I declare a class names your and in class, i declare a constructor which has the same name like as class. and after that, I declare the code in between the constructor. after that, i create the object of the class. when we create the object of the class the constructor of the class is automatically called and execute the code within the constructor.

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

0 comments: