Reputation: 55
I am learning c++, and I came across following code segment:
class X
{
int i;
public:
X(int ii = 0);
void modify();
};
X::X(int ii)
{ i = ii; }
void X::modify()
{ i++; }
X f5()
{ return X(); }
const X f6()
{ return X(); }
void f7(X& x) // Pass by non-const reference
{ x.modify(); }
int main()
{
f5() = X(1);
f5().modify();
}
I am stuck particularly in this segment-
X f5()
{ return X(); }
Does this part of code return an object of type x by value? Can a constructor return an object?
Upvotes: 0
Views: 2468
Reputation: 1426
simple, you misunderstand the constructor of the class and a function. your class class X
have a constructor and it is X(int ii = 0);
.
X f5()
is not a constructor. Clearly understand that first.
Constructor of a class should have the same name as class and have no a return value. It does,t make any sense. (read further about class and constructor)
X f5() {
return X();
}
This is a function which returns a X
type of object. it returns the X().
X()
creates a value-initialized temporary object of type X
.
Upvotes: 1
Reputation: 254771
Does this part of code returns an object of type x by value?
Yes, it creates and value-initialises a temporary object of type X
(by calling the constructor with the default value of zero) and returns that.
can a constructor can return an object?
No, that doesn't make any sense. But an conversion expression like X()
does.
Upvotes: 4
Reputation: 55897
f5
is just function, not constructor. And it returns constructed object of type X
.
Upvotes: 3