Possible Duplicate:
std::string x(x);
class A {};
int main() {
A a(a);
}
This compiles.
gcc (GCC) 4.7.2 20120921 (Red Hat 4.7.2-2)
g++ -o main main.cpp -Wall -w -ansi
I receive no warnings.
Why does this appear to be valid C++?
Is this mentioned anywhere in the standard?
Are there warning flags that can report this for gcc?
When the class has member data, the data ends up random.
example:
#include <iostream>
class A {
public:
int i;
A() : i{6} {}
};
int main() {
A a(a);
std::cout << a.i << '\n';
}
output: -482728464
What's going on here? Also, how can I prevent myself from accidently doing this? - Is it possible to make it a compiler error?
It is necessary to pass object as reference and not by value because if you pass it by value its copy is constructed using the copy constructor. This means the copy constructor would call itself to make copy. This process will go on until the compiler runs out of memory.
A copy constructor has the following general function prototype: ClassName (const ClassName &old_obj); Copy constructor is used to initialize the members of a newly created object by copying the members of an already existing object. Copy constructor takes a reference to an object of the same class as an argument.
Answer: No, in C++, a copy constructor doesn't support pass by value but pass by reference only. It cannot accept object parameter by value and it should always receive it as a reference.
Why copy constructor argument should be const in C++? When we create our own copy constructor, we pass an object by reference and we generally pass it as a const reference. One reason for passing const reference is, we should use const in C++ wherever possible so that objects are not accidentally modified.
(§ 3.3.2/1) The point of declaration for a name is immediately after its complete declarator (Clause 8) and before its initializer (if any), except as noted below. [ Example:
int x = 12; { int x = x; }
Here the second x is initialized with its own (indeterminate) value. —end example ]
This applies to user-defined types, such as your class A
, as well. The copy constructor used is the default one, auto-generated by the compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With