Programmingoneonone is known for sharing best programming knowledge.

copy constructor in c++ programming

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


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

copy constructor:

a copy constructor is used to create one object using another object. 

syntext:
           class <class-name>
           {
               public:

                  <class-name>(const classname &object)
                  {
                    code for execution;
                  }
          };

Example:
               class your
              {
                 public:

                   your( const your &obj) // copy constructor 
                   {
                      code for execution;
                   }
             };


Example program using copy constructor:

  #include <iostream>

  class test
  {

         int a;
         float f;

         public:

           test(int b, float c) // parameterized constructor
           {
              a=b;
              f=c;
             std::cout<<"\n vlaue of a and f is:"<<a <<f;
           }
           test(const test &t) //copy constructor
           {
              a= t.b;
              f= t.c;
           }

  };

  int main()
  {
     test t1(10, 10.1); // call the parameterized constructor
     test t2(t1);  // call the copy constructor. 

     return 0;
  }

Note: to call the constructor you need to give the same parameter when creating an object. like if you declare a constructor which has no any parameter then you need not to pass any parameter to the constructor when you creating an object. 
in the above example we create the two constructors one is parameterized constructor and one is a copy constructor. so to call the parameterized constructor we need to give the parameter and pass the value at the creating time of an object. and to call the copy constructor we need to pass the object when creating the object of the class. 

"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