Question:
C++ When does the compiler provide copy constructor?
2010-04-06 14:40:39 UTC
If I declare a public constructor CExample (int a, int b), and I use these two object declarations:
CExample ex (2,3);
CExample ex2 (ex);

1) Does this mean the copy constructor is provided (in contrast to the default provider) even though I have my own constructor (int a, int b)
2) CExample ex2 = ex; // Is this equivalent to that second line?
3) In a nutshell, what does a copy assignment operator do?
Three answers:
Cubbi
2010-04-07 06:42:47 UTC
1) Yes, under ISO 14882:2003 paragraph 12.8:

"If the class definition does not explicitly declare a copy constructor, one is declared implicitly."



2) Yes, CExample ex2(ex); and CExample ex2 = ex; are the same, both are examples of initialization by copy construction as described in ISO 14882:2003 paragraph 12.6.1

" An object of class type can be initialized with a parenthesized expression-list, where the expression-list is construed as an argument list for a constructor that is called to initialize the object. Alternatively, a single assignment-expression can be specified as an initializer using the = form of initialization. Either direct initialization semantics or copy-initialization semantics apply"



3) I'm glad you call it "copy assignment operator" because that's the only correct name of X::operator=(X&) in C++98 (and in C++0x there's also going to be a move assignment operator). As for what it does, It copies the object into an already existing object, unlike copy constructor, which copies an object into a nascent, not-yet-existing object.
Mark
2010-04-06 15:31:30 UTC
1) The compiler always provides a copy constructor. You only need to provide your own if there are special circumstances, like your class containing pointers as members.

2) Your example is equivalent, but the underlying behaviour is not. Check out http://en.wikipedia.org/wiki/Assignment_operator_in_C%2B%2B and http://en.wikipedia.org/wiki/Copy_constructor for explanations.

3) I'm not sure what you mean by "copy assignment operator". Do you just mean assignment operator (=)?
?
2016-12-02 00:50:51 UTC
You suggested to describe whats occurring interior the line: return a(); // what's befell right here? nicely, right here you're returning a cost however the challenge is you're returning it with parenthesis. It shouldn't incorporate paranthesis. in simple terms use the term return a;


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...