简体   繁体   中英

C++ - Using a copy constructor when returning an object-pointers?

There are three reasons why you should use a copy constructor when your class has a pointer. One of those is when a function returns a value of the class type. I was wondering what that meant? My guess is.

for instance...when we overload an operator we can return an object with a class constructor rite?

height(feet, inches);//normal constructor...feet and inches representing two private members

const height operator+ (const height& height1, const height& height2)
{
     int finalFeet = height1.getFeet() + height2.getFeet();
     int finalInches = height1.getInches() + height2.getInches();
     return height(finalFeet, finalInches);
}

So, I'm guessing that a copy constructor would be needed if the private members feet and inches were pointers. instead of the constructor height(feet, inches); The copy constructor would be called like so, height(const height& rightHead); Am I correct?

Something I just realized is that if we return an object within its own class we can just say *this and if it were function outside the class we use a constructor to return the type.

Thanks!

When you return by value, you're returning an object. If you return an object you must create an object. Therefore you must call a ctor.

In your example, the operator+ returns a new object therefore don't return *this . operator+= modifies the current object and in that case you can return *this .

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