Hi .. the below code is generating an error of No matching function for call to room::room(room). Can anyone clarify .. ?? Am getting error at: room room2 = room (2); statement . As per my knowledge, expecting the program to
1. call default constructor to initialize room1
2. call default constructor to initialize temporary object
3. calling copy constructor that is defined here to construct room2 with the help of temporary object..
Pl reply if any wrong in my analysis..
#include <iostream>
using namespace std;
class room
{ int x;
public :
room () { x=1; }
room (int y) { x=y; }
room (room & temp) { x=temp.x; }
Hi Cire.. Many thanks for ur quick reply.. Tried with given const in copy constructor, it is not generating any error, but, got another problem.. My program & its output are given below
#include <iostream>
usingnamespace std;
class room
{
int x;
public :
room () : x(1) { cout <<"Default empty constructor called"<<endl<<endl; }
room (int y): x(y) { cout <<"Constructor with int argument is called " <<endl<<endl; }
room (const room & temp):x(temp.x) { cout <<"Copy constructor is called " <<endl<<endl; }
void disp() {cout << x;}
};
int main ()
{
room room1;
room room2 = room (2);
cout << "Value x of room1 is : "; room1.disp(); cout <<endl<<endl;
cout << "Value x of room2 is : "; room2.disp(); cout <<endl<<endl;
system("PAUSE");
return 0;
}
Output : Default empty constructor called
Constructor with int argument is called
Value x of room1 is : 1
Value x of room2 is : 2
Can you pl suggest why it is not executing defined copy constructor after building temporary object at room room2 = room (2); statement.. I believe it is supposed to assign temporary object contents to room2 with the help of defined copy constructor. But it is not at all calling defined copy constructor.. Pl clarify..
Thank God.. Understood the statement perfectly.. at room room2 = room (2); , it is simply creating 'room' type object 'room2' and passing argument of '2' to its constructor.. Thats what this kind of statement does.. My earlier understanding of the same statement was wrong.. ;( ... Thanks Cire..
Yes, in order for that statement to work correctly the copy constructor must have the correct signature, but the compiler is allowed to use copy elision under the as-if rule.