Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple constructors in C++

Question is about multiple constructors that confuses me.

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

using namespace std;

Complex::Complex(double realPart, double imPart)
    : m_R(realPart), m_I(imPart)
{
    cout << "complex(" << m_R << "," << m_I << ")" << endl;
}

Complex::Complex(double realPart)
{
    Complex(realPart, 0);
}

Complex::Complex() : m_R(0.0), m_I(0.0)
{
}

int main() {
    Complex C1;
    Complex C2(3.14);
    Complex C3(6.2, 10.23);
}

Can someone explain how compiler knows which constructor to use of three defined? Primer is from this book, page 58.

like image 620
Inception Avatar asked Oct 23 '25 16:10

Inception


1 Answers

Side Note

If you want to utilize C++ 11 delegating constructors you should write:

Complex::Complex(double realPart) 
:    Complex(realPart, 0)
{}

instead of

Complex::Complex(double realPart) {
    Complex(realPart, 0);
    }

which creates a temporary unused Complex inside the constructor body.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!