I just have learned OOP in c++ today but I met a weird problem when I am trying to do things as follows:
- 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
- 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);
}
- 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.