简体   繁体   中英

Return type of a constructor in c++

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?

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.

f5 is just function, not constructor. And it returns constructed object of type X .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM