Confusion with copy constructor and non-const values

How does cmplex c1=cmplex(2,3) creates temporary object here?..please give me detailed explaination
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
     
using namespace std;
     
class cmplex
{
int a,b;
public:
cmplex(int x,int y){a=x;b=y;cout<<"its inside constructor 1"<<a<<" "<<b<<endl;}
cmplex(cmplex &c){a=c.a;b=c.b;cout<<"its inside copy constructor 1"<<endl;cout<<a<<b<<endl;}
};
int main()
{
cmplex c1=cmplex(2,3);
return 0;
}

this code does not run,as at line no 10 i have to add cmplex(const cmplex &c) instead of cmplex(cmplex &c)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
     
using namespace std;
     
class cmplex
{
int a,b;
public:
cmplex(int x,int y){a=x;b=y;cout<<"its inside constructor 1"<<a<<" "<<b<<endl;}
cmplex(const cmplex &c){a=c.a;b=c.b;cout<<"its inside copy constructor 1"<<endl;cout<<a<<b<<endl;}
};
int main()
{
cmplex c1=cmplex(2,3);
return 0;
}

this code runs
but look at this code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
     
using namespace std;
     
class cmplex
{
int a,b;
public:
cmplex(int x,int y){a=x;b=y;cout<<"its inside constructor 1"<<a<<" "<<b<<endl;}
cmplex(cmplex &c){a=c.a;b=c.b;cout<<"its inside copy constructor 1"<<endl;cout<<a<<b<<endl;}
};
int main()
{
cmplex c1(2,3);
return 0;
}

	

this code runs without adding const. why is this happening. I am only using cmplex c1(2,3) instead of cmplex c1=cmplex(2,3) at line 14.

My question is, "Is somehow cmplex c1=cmplex(2,3) is creating a temporary object or something else"?
Last edited on
this code runs without adding const. why is this happening. I am only using cmplex c1(2,3) instead of cmplex c1=cmplex(2,3) at line 14.
The constructor on line 9 is called.

My question is, "Is somehow cmplex c1=cmplex(2,3) is creating a temporary object or something else"?
While this is theoretical true but read this:

http://en.cppreference.com/w/cpp/language/copy_elision

Thus the copy constructor is not called. You can comment it out and everything will work fine.

Normally you don't need to write your own copy constructor because the compiler generates one if necessary. The non const copy constructor prevents this.

A non const reference expects a lvalue:

http://en.cppreference.com/w/cpp/language/value_category

Which means it can be used left of the assignment. A temporary object like cmplex(2,3) is not an lvalue hence you cannot pass it to a non const reference.
Thanks a lot
Topic archived. No new replies allowed.