Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can you call a copy constructor passing in the object you are constructing? (C++) (gcc) [duplicate]

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?

like image 524
Trevor Hickey Avatar asked Oct 09 '12 01:10

Trevor Hickey


People also ask

Why do we pass object as reference in copy constructor?

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.

How do you call a copy constructor in C++?

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.

Can a copy constructor accept an object of the same class as parameter instead of reference of the object?

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++?

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.


1 Answers

(§ 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.

like image 71
jogojapan Avatar answered Oct 01 '22 21:10

jogojapan