There is this code:
class SomeClass
{
public:
SomeClass(){}
SomeClass(SomeClass& b){}
SomeClass(SomeClass&b, SomeClass& c){}
};
int main()
{
SomeClass a;
SomeClass(); // works all right
//SomeClass(a); error: redeclaration of ‘SomeClass a’
SomeClass(a, a); // works all right
return 0;
}
Anonymous object of SomeClass with 0 and 2 parameters can be declared, however it cannot be declared with only 1 argument. I assume that writing
SomeClass(a);
is the same as
SomeClass a;
How to create anonymous object with one argument?
You can construct a temporary object in a statement of its own with something like:
(SomeClass)a;
or
(SomeClass(a));
As you've observed, the parentheses are needed to resolve the ambiguity between a declaration and an expression statement.
You can create that anonymouse object as the following:
(SomeClass(a));
This resolves the ambiguity since it can't be a declaration of a.
(SomeClass a); // Error: this can't be a declaration because of the parentheses
// but what else should it be?
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