Reputation: 161
I understand everything about the following code, except this line
A f(){return A(i);}
Specifically I don't understand the syntax A(i)
. I know it returns a value of the type A
but what does the i
in the brackets mean?
Is it a constructor call with some variable?
#include <iostream>
using namespace ::std;
class A{
public:
int j;
A(int z){j = z;}
int g(){return j;}
int operator+(A a){return a.j + j;}
};
class B{
public:
int i;
B(A a){i = a.j;}
A f(){return A(i);} // ???
A operator-(){return A(i);}
};
int main(){
A a(1);
B b = a;
a.j = b.f() + a;
b.i = a.g();
a = -b;
return 0;
}
Upvotes: 2
Views: 87
Reputation: 170084
A(i)
is a functional cast expression. It's creating a temporary object A
from i
. The process will call the appropriate A
constructor.
In C++ there is no way for the programmer to "call the constructor". What the programmer does is create objects at all sorts of places, and the construction is arranged automatically. A functional cast expression is one such way to create an object.
And mind you, that while this is formally "creating a temporary", copy elision (return value optimization) will actually make it initialize the return value directly.
Upvotes: 6