简体   繁体   中英

Strange behaviour of copy constructor

I'm new to c++ programming and like others i find the copy constructor concept a bit stange.I went through a site which said

The copy constructor is a special kind of constructor which creates a new object which is a copy of an existing one, and does it efficiently.

I wrote a code to create an object which is a copy of an other object and found the results to be strange the code is as below .

 #include <iostream>

 using namespace std;

 class box
 {
   public:

   double getwidth();
   box(double );
   ~box();
    box(box &);
   private:
      double width;
 };

box::box(double w)
{
   cout<<"\n I'm inside the constructor ";
   width=w;
}

box::box(box & a)
{
  cout<<"\n Copy constructructor got activated ";
}
box::~box()
{
  cout<<"\n I'm inside the desstructor ";

}

double box::getwidth()
{
   return width;
}


int main()
{
  box box1(10);
  box box2(box1);
  cout<<"\n calling getwidth from first object  : " <<box1.getwidth();
  cout<<"\n calling the getwidth from second object   : " <<box2.getwidth(); 
}

When i called box2.getwidth() as per the code below i got a junk value . I expected the width to be initialized to 10 as the box2 is copy of box1 as per my understanding .Please clarify

Your expectation was that all members are copied automagically, but they're not (not if you provide your own implementation). You'll need to add the logic yourself:

box::box(const box & a)
{
  width = a.width;
  cout<<"\n Copy constructructor got activated ";
}

Your version tells the compiler - "whenver you make a copy, print out that thing", which it does. You never instruct it to copy any of the members.

Just FYI, if you provide no implementation, the compiler will generate a copy constructor for you, which does a shallow, memberwise copy.

Write your copy ctor like this. Your copy constructor code doesn't copy the object contents.

box::box(box & a):width(a.width)
{
  cout<<"\n Copy constructructor got activated ";
}
int main()
{
box a(10);

box b = a;//copy constructor is called
return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM