What's the output of the program?
#include <iostream>

class A
{
public:
    A(int n = 2) : m_i(n) { }

    ~A() { std::cout << m_i; }

protected:
    int m_i;
};

class B
    : public A
{
public:
    B(int n) : m_a1(m_i + 1), m_a2(n) { }

public:
    ~B()
    {
        std::cout << m_i;
        --m_i;
    }

private:
    A m_a1;
    A m_a2;
};

int main()
{
    { B b(5); }

    std::cout << std::endl;

    return 0;
}
Explanation
Here the order of execution of constructors and destructors plays a role. First, the constructor of the class is executed and then m_a1 and m_a2 and then the constructor of class B. The same thing is executed at destruction only in reverse order. Destructor B, m_a2, m_a1, Destructor A.

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Cosmo
Зареєструйся Зараз
або Підпишись на майбутні тести