0

I just have learned OOP in c++ today but I met a weird problem when I am trying to do things as follows:

  1. Complex.h

#ifndef LEETCODE_COMPLEX_H
#define LEETCODE_COMPLEX_H

#include <iostream>

class Complex {
private:
    double _real;
    double _image;

public:
    Complex();

    Complex(double real, double image);

    Complex(const Complex &rhs);

    virtual ~Complex();

    Complex &operator=(const Complex &rhs);

    Complex operator+(const Complex &rhs) const;
};


#endif //LEETCODE_COMPLEX_H

  1. Complex.cpp

#include "Complex.h"
#include <iostream>

Complex::Complex(double real, double image) {
    _real = real;
    _image = image;
    std::cout << "Complex::Complex(double real, double image)" << std::endl;
}

Complex::Complex() : _real(0), _image(0) {
    std::cout << "Complex::Complex()" << std::endl;
}

Complex::~Complex() {
    std::cout << "~Complex" << std::endl;
}

Complex &Complex::operator=(const Complex &rhs) {
    if (this != &rhs) {
        _real = rhs._real;
        _image = rhs._image;
    }
    return *this;
}

Complex::Complex(const Complex &rhs) : _real(rhs._real), _image(rhs._image) {
    std::cout << "Complex::Complex(const Complex &rhs)" << std::endl;
}

Complex Complex::operator+(const Complex &rhs) const {
    return Complex(_real + rhs._real, _image + rhs._image);
}

  1. main.cpp
#include "Complex.h"

int main() {

    Complex a(1, 2);
    Complex b;
    Complex c = a + b;
    return 0;
}

Question: What I trying to do is to create Complex a and Complex b, and, create Complex c by adding a and b. This is the procedure that I used to figure out what constructor they will use. And as we can see, I put some messages in constructor which can help me to check what constructor was used. What surprise me is that the output is:

Complex::Complex(double real, double image)
Complex::Complex()
Complex::Complex(double real, double image)
~Complex
~Complex
~Complex

Because I have wrote Complex operator+(const Complex &rhs) const;, I think that the last Complex::Complex(double real, double image) is print by this function. But I think c should have a constructor as well, which should print another message, and what I want to know is that. I guesses c may just be a pointer that points (a+b), but I also believe c should be created by copy constructor.

MrZ
  • 166
  • 1
  • 1
  • 11
  • You're about to learn how awesome C++ is, and C++ compilers are. They are able to figure out a way to optimize away a completely unnecessary copy construction. The `return` in the `operator+` overload actually ends up constructing `c` in your `main()` (in so many words). – Sam Varshavchik Jan 23 '21 at 14:35
  • Here's a good read about so-called *copy elision* (though it's quite technical): https://stackoverflow.com/q/12953127/10871073 – Adrian Mole Jan 23 '21 at 14:42
  • @SamVarshavchik thanks a lot, I think I have to learned more before I can understand this. – MrZ Jan 23 '21 at 14:48

0 Answers0