Why the following code (create function) calls the copy constructor when it returns an object? I know that this is one of the cases where the copy constructor is getting called. But what is the reason? I'm not copying an object or assigning a reference using = operator.
The same kind of behavior comes when we throw an object, I think.
Please clarify.
Thanks,
Jos Collin
-----------------------------------------------
#include <iostream>
using namespace std;
class ABC
{
int a;
int b;
public:
ABC()
{
cout << "constructor called\n";
}
ABC(ABC& x)
{
a = x.a;
b = x.b;
cout << "copy constructor called\n";
}
void printdata()
{
cout << a << b;
}
void assigndata()
{
a=1;b=2;
}
};
class XYZ
{
private:
ABC *p;
public:
ABC create()
{
p = new ABC();
p->assigndata();
return *p;
}
};
int main()
{
ABC a1;a1.assigndata();
XYZ x1; x1.create();
Returning an object by value means returning a copy. Same with passing parameters by value.
Why are you returning anything from create() anyway? Either remove the return value or return a reference.
And the calls to assigndata() and create() belong into their respective constructors. That's what they exist for.
For example the std containers that require a copy constructor, are looking for one with the sigunature (const ABC& x).
if it is not there, a default copy constructor will be used instead of the one you wrote. so it is not just proper conduct.
ABC(ABC& x) // <- would you change 'x' in this function?
// no. So it should be a const reference
Problems can arrise if you fail to do this. For example, if you try to copy a const object, the non-const reference can't be used:
1 2 3 4
const ABC a; // a const ABC object
ABC copy(a); // copy of 'a'. Note that since 'a' is const, the copy constructor
// must accept a const reference. A non-const reference won't fly.
Returning an object by value means returning a copy. Same with passing parameters by value.
I was wondering if all the return statements in C and C++ returns a copy or not? If so where the copy is created? Will it be inside create() or in the main function, so that I could call x1.create().printdata() ? Please help me by explaining in detail. I hope the same happens duding throw.
Why are you returning anything from create() anyway? Either remove the return value or return a reference.
I'm returning the object from create() to test if the copy constructor is called or not. I have read it in a book and want to test the return, throw statements. So I have written a code that does the same and didn't care about the perfection.
And the calls to assigndata() and create() belong into their respective constructors. That's what they exist for.
I know that the code is not perfect. I just wrote it with an intention of checking the behavior of the return statement.
I know that there should be const. I have written this code very fast to check the behavior of the return statement. So I missed it. if the Other people could answer to the topic, it would be great.