Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this class object declaration work?

Tags:

c++

oop

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?

like image 434
Vidit Virmani Avatar asked Oct 04 '18 04:10

Vidit Virmani


2 Answers

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.

like image 197
Chris Dodd Avatar answered Nov 15 '22 00:11

Chris Dodd


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.

like image 42
P.W Avatar answered Nov 14 '22 22:11

P.W