jeudi 27 décembre 2018

confusion in direct initialization vs copy initialization in C++

I have this code snippet:

class Fraction
{
private:
    int m_numerator;
    int m_denominator;

public:

    // Default constructor
    Fraction(int numerator = 0, int denominator = 1) :
    m_numerator(numerator), m_denominator(denominator)
    {
        std::cout << "Default constructor called!\n";
        assert(denominator != 0);
    }

    // Copy constructor
    Fraction(const Fraction &frac) :
    m_numerator(frac.m_numerator), m_denominator(frac.m_denominator)
    {
        std::cout << "Copy constructor called!\n";
    }

    friend std::ostream& operator<<(std::ostream& out, const Fraction &f1);
};

std::ostream& operator<<(std::ostream& out, const Fraction &f1)
{
    out << f1.m_numerator << "/" << f1.m_denominator;
    return out;
}

int main(int argc, const char * argv[]) {
    Fraction one(Fraction(6,3));//direct initialization??, with default constructor
    Fraction second = one;//copy initialization with copy constructor
    Fraction third(one);////direct initialization, but with copy constructor???
    return 0;
}

when I run this program ,I get the following result in the console:

Default constructor called!
Copy constructor called!
Copy constructor called!

My first question is, in this line:

Fraction one(Fraction(6,3));//direct initialization??, with default constructor

why is this not a copy initialization with the copy constructor? My understanding is that a Fraction object is initialized first and then it is copied into another Fraction object called "one"

and second question is,

Fraction third(one);////direct initialization, but with copy constructor???

It seems like you can mix a direct initialization with using a copy constructor, so this is possible?

and third question is, Can I assume that direct initialization will always use a pair of () while copy initialization will always use the equal sign?

Thanks very much!

Aucun commentaire:

Enregistrer un commentaire