Reputation: 9
class A
{
public:
A() { cout << "constructor" << endl; };
A(const A &) { cout << "copy constructor" << endl; };
void operator()(int a, int b) { cout << "a+b" << endl; }
};
void set(A visit) {
visit(1, 2);
}
int main()
{
set(A());
return 0;
}
The A() constructor directly creates an access to an object that is passed to the set parameter by an implicit object. The constructor also has the ability to create objects?
Upvotes: 0
Views: 66
Reputation: 473397
You have this backwards. A()
creates an object of type A
. As part of this process, this syntax invokes a constructor of A
if it has one. After all, you can do int(5)
to create an int
, but this doesn't mean int
has a constructor (only user-defined types have actual constructors/destructors).
So it's not really that you're "calling a constructor which happens to create an object"; you're instead "creating an object, which may involve calling a constructor".
Upvotes: 2
Reputation: 26800
Yes. The manner in which you are constructing the object in the line:
set(A());
is called functional notation type conversion. This is specified in the section on constructors in the CPP standard draft.
A constructor is used to initialize objects of its class type. Because constructors do not have names, they are never found during name lookup; however an explicit type conversion using the functional notation will cause a constructor to be called to initialize an object. [ Note: The syntax looks like an explicit call of the constructor. — end note ]
complex zz = complex(1,2.3); cprint( complex(7.8,1.2) );
An object created in this way is unnamed.
Upvotes: 3