i gave the copy constructor in the below code just to know when will it be called..

#include<iostream>
using namespace std;
class counter
{
  int val;

public:
  ~counter()
  {
    cout<<"destructor"<<endl;
  }
  
  counter(counter&)
  {
    cout<<"copy constructor called"<<endl;
  }

  counter():val(0)
  {}
  counter& operator++()
  {
    ++val;
    *this;
  }

  int getval()
  {
    return val;
  }
};

int main()
{
  counter i;
  cout<<"the value is"<<i.getval()<<endl;
  ++i;
  cout<<"the value is"<<i.getval()<<endl;
  counter a=++i;
  cout<<"the value is"<<i.getval()<<endl;
  cout<<"the value is"<<a.getval()<<endl;
}

i am getting the wrong output:
the value is 0
the value is 1
copy constructor called
the value is 2
the value is 1628937800
destructor
destructor

if i comment the copy constructor i am getting the correct output:
the value is 0
the value is 1
copy constructor called
the value is 2
the value is 2
destructor
destructor

can someone pls help me!!

The purpose of the copy constructor is to create a copy of the object used to create the new object. In order to do that, you must copy the data from the original object to the new object; the information transfer doesn't happen automagically. You're getting a bad output value from a.getval() because you are leaving counter::val uninitialized in the copy (the object called "a"). Your copy constructor should be:

counter(const counter &otherCounter) : val(otherCounter.val)
  {
    cout<<"copy constructor called"<<endl;
  }

Notice the "otherCounter" object (which is a constant reference) and the "val" initializer...

Edited 5 Years Ago by Fbody: n/a

There is always a default copy constructor which does a shallow copy for you. In your case that would be enough to make your code work. But since YOU define now a copy constructor, you override the default copy constructor. In your copy constructor, there's only an output going to the console, but nothing is said about initializing the member variable val. That's why you get this odd value for the object a.

There is always a default copy constructor which does a shallow copy for you. In your case that would be enough to make your code work. But since YOU define now a copy constructor, you override the default copy constructor. In your copy constructor, there's only an output going to the console, but nothing is said about initializing the member variable val. That's why you get this odd value for the object a.

You are correct that the compiler will provide one automatically and it would be sufficient for this class. I suspect though that this is some sort of coursework exercise.

This article has been dead for over six months. Start a new discussion instead.