copy constructor

i gave the copy constructor in the below code just to know when will it be called..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#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 copy constructor is not copying anything so it leaves val uninitialized.
Also, the copy constructor should take a const reference
if you want to write your own copy constructor
you have the responsibilities to copy all of the data you need
the nasty part of the self define copy constructor is--they wouldn't told you you didn't copy all
of the data you have to copy

usually we don't need to mess-up with self defined copy constructor if we
didn't do any dynamic memory allocation
but it is a good practice to play with self defined copy constructor since the
containers of the standard may not satisfied some special applications

But most of the time stl is good enough to handle those applications
I do hope someday I could create those containers and algorithms like stl did
Last edited on
Also, your operator++ doesn't actually return anything -- you are missing the return keyword.

Topic archived. No new replies allowed.