I am trying to understand some aspects of C ++.
I wrote this short program to show different ways to return objects from functions in C ++:
using namespace std;
class Car{
private:
int maxSpeed;
public:
Car( int );
void print();
Car& operator= (const Car &);
Car(const Car &);
};
Car::Car( int maxSpeed ){
this -> maxSpeed = maxSpeed;
cout << "Constructor: New Car (speed="<<maxSpeed<<") at " << this << endl;
}
Car& Car::operator= (const Car &anotherCar){
cout << "Assignment operator: copying " << &anotherCar << " into " << this << endl;
this -> maxSpeed = anotherCar.maxSpeed;
return *this;
}
Car::Car(const Car &anotherCar ) {
cout << "Copy constructor: copying " << &anotherCar << " into " << this << endl;
this->maxSpeed = anotherCar.maxSpeed;
}
void Car::print(){
cout << "Print: Car (speed=" << maxSpeed << ") at " << this << endl;
}
Car makeNewCarCopy(){
Car c(120);
return c;
}
Car& makeNewCarRef(){
Car c(60);
return c;
}
Car* makeNewCarPointer(){
Car * pt = new Car(30);
return pt;
}
int main(){
Car a(1),c(2);
Car *b = new Car(a);
a.print();
a = c;
a.print();
Car copyC = makeNewCarCopy();
copyC.print();
Car &refC = makeNewCarRef();
refC.print();
Car *ptC = makeNewCarPointer();
if (ptC!=NULL){
ptC -> print();
delete ptC;
} else {
}
}
The code does not seem to crash, and I get the following output:
Constructor: New Car (speed=1) at 0x7fff51be7a38
Constructor: New Car (speed=2) at 0x7fff51be7a30
Copy constructor: copying 0x7fff51be7a38 into 0x7ff60b4000e0
Print: Car (speed=1) at 0x7fff51be7a38
Assignment operator: copying 0x7fff51be7a30 into 0x7fff51be7a38
Print: Car (speed=2) at 0x7fff51be7a38
Constructor: New Car (speed=120) at 0x7fff51be7a20
Print: Car (speed=120) at 0x7fff51be7a20
Constructor: New Car (speed=60) at 0x7fff51be79c8
Print: Car (speed=60) at 0x7fff51be79c8
Constructor: New Car (speed=30) at 0x7ff60b403a60
Print: Car (speed=30) at 0x7ff60b403a60
Now I have the following questions:
- Is makeNewCarCopy safe? Is a local object copied and destroyed at the end of the function? If so, why doesn't it call the overloaded assignment operator? Does it invoke the default copy constructor?
- My courage tells me to use it
makeNewCarPointeras the most common way to return objects from a C ++ function / method. I'm right?
source
share