Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous object with one argument cannot be declared

Tags:

c++

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?

like image 1000
scdmb Avatar asked Sep 26 '26 18:09

scdmb


2 Answers

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.

like image 184
CB Bailey Avatar answered Sep 30 '26 20:09

CB Bailey


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?
like image 34
ipc Avatar answered Sep 30 '26 21:09

ipc