lundi 27 juin 2016

C++ - order of member initialization and incrementation


I was looking for some tests to improve my C++ knowledge. Here is one of the exercises: What is the output of the following program?

#include <iostream>

class A
{
public:
    A(int n = 0) : m_i(n)
    {
        std::cout << m_i;
        ++m_i;
    }

protected:
    int m_i;
};

class B : public A
{
public:
    B(int n = 5) : m_a(new A[2]), m_x(++m_i) { std::cout << m_i; }

    ~B() { delete [] m_a; }

private:
    A m_x;
    A *m_a;
};

int main()
{
    B b;
    std::cout << std::endl;
    return 0;
}

Well, I tried this code, and the answer is 02002. I come here to have some explanation because I don't understand why 02002 is the result. I will explain my reasoning, but could some tell me where am I wrong please?

Let's call "str" the current string to print. When the b object is built:

  1. The constructor of A is called. str => 0, m_i => 1
  2. Construction of m_a(new A[2]). str => 000
  3. Construction of m_x(++m_i). str => 0002, m_i => 3
  4. Last update of str (in B's constructor) => str => 00023

Here are my questions:

  • Why is the final value of m_i 2 and not 3?
  • Why is the construction of m_x(++m_i) done before the one of m_a(new A[2])? I tried to exchange the position of the initialization of m_x and m_a and the answer is still the same : 02002.

Aucun commentaire:

Enregistrer un commentaire