copy constrctor

Jun 14, 2013 at 8:18am
i defined a class sample like this..


class sample
{ int i;
public:
explicit sample(int a)
{ i=a;
cout<<"i amin constructor"<<endl;
}

sample(sample &s)
{ i=s.i;
cout<<"i am in copy constructor"<<endl;
}
void display()
{ cout<<" i am in display";
}

};



and if i write this statement in the main
sample r=sample(8);

it is throwing following error...

explicitk.cpp:31:21: error: no matching function for call to ‘sample::sample(sample)’
explicitk.cpp:31:21: note: candidate is:
explicitk.cpp:14:1: note: sample::sample(sample&)
explicitk.cpp:14:1: note: no known conversion for argument 1 from ‘sample’ to ‘sample&’



please help me with this ...i am new to c++


thanks
Venkata prasad manne


Jun 14, 2013 at 9:30am
A copy constructor is expecting a parameter of the same class type.

You're passing an integer.

Here's a simple example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

struct MyStruct
{
  int a;
  MyStruct():a(10){}
  MyStruct( const MyStruct &other )
  {
    this->a = other.a;
  }
};

int main( int argc, char* argv[] )
{
  MyStruct firstStruct; // Runs normal constructor, a is 10
  firstStruct.a = 4;    // Let's change the value
  MyStruct secondStruct( firstStruct ); // Copies the first struct

  std::cout << "Value of a in secondStruct is " << secondStruct.a << std::endl;

  return 0;
}
Last edited on Jun 14, 2013 at 9:31am
Jun 14, 2013 at 9:35am
Yes, he's calling the custom constructor which will work. Also, using his code if he were to call the copy constructor, he shouldn't get the error he is apparently getting. If I just copy his code it all compiles and works and if I just add a further line to the main function:

 
sample r2 = sample(r);


All still compiles and works fine!
Jun 14, 2013 at 9:38am
The problem is that you defined the copy constructor as haveing as the parameter non-const reference to class object.
In this statement

sample r=sample(8);

at first a temporary object of type sample is created using constructor explicit sample( int ):

sample( 8 )

A temporary object can be binded with const reference. So apart from the copy constructor sample( sample & ) you need copy constructor sample( const sample &). Your code could be compiled if you would write

sample t( 8 );
sample r=t;

In this case your copy constructor would be called because t is not a temporary object.

It is enough to have only one copy constructor defined as
sample( const sample & )
It will be called for temporary and non-temporary objects.

Last edited on Jun 14, 2013 at 9:40am
Jun 14, 2013 at 9:44am
@ajh32

Whoops, my bad. I missed the constructor with the integer parameter there. :-S
Last edited on Jun 14, 2013 at 9:45am
Jun 16, 2013 at 7:31pm
THanks evryone for replying .....and thanks vaidfrommosow for ur exact answer..



Topic archived. No new replies allowed.