Suppose I have a class
class Test{
public:
int x;
Test(const Test& obj){x=obj.x;}
};
Why does
Test object_name(Test random_name);
run and does not need another object as a parameter?.
.Something like Test random_name(Test another_random(...))
, making it a never ending way of declaring the object?
This line:
Test object_name(Test random_name);
declares a function called object_name
that takes a Test
as a paramter and returns a Test
. It does not declare an object. It is perfectly legal to declare a function like this inside another function, it's just implicitly extern
.
Substitute Test
with a PoD like int
and you will see what is happening
Test object_name(Test random_name); //1
int object_name(int random_name); //2
You can see that the second statement is a function declaration which takes an int
as argument and returns an int
.
This is due to a well-known rule in CPP related to ambiguity resolution.
From the CPP working draft (N4713):
9.8 Ambiguity resolution [stmt.ambig]
1 There is an ambiguity in the grammar involving expression-statements and declarations: An expression-statement with a function-style explicit type conversion as its leftmost subexpression can be indistinguishable from a declaration where the first declarator starts with a (. In those cases the statement is a declaration.
2 [ Note: If the statement cannot syntactically be a declaration, there is no ambiguity, so this rule does not apply. The whole statement might need to be examined to determine whether this is the case.
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