Domanda

How does below program evaluates to following? 1. How is the parameterized constructor evaluated? left to right ?

ZA (int n)0 ---> base class constructor called.

ZA (int n)2 --> how does m_i = 2 here?

ZA (int n)0 ----> constructor for ZA member variable defined in Zb called

ZA (int n)0

ZB (int n)2

#include <iostream>
using namespace std;

class ZA
{
public:
    ZA(int n = 0) : m_i(n) 
    {
        std::cout <<"ZA (int n)" <<m_i<<endl;
        ++m_i;
    }
protected:
    int m_i;
};

class ZB : public ZA
{
public:
    ZB(int n = 5) : m_a(new ZA[2]), m_x(++m_i)
    {
        std::cout <<"ZB (int n)" <<m_i<<endl;
    }
    ~ZB() 
    {
        delete [] m_a; 
    }
private:
    ZA m_x;
    ZA *m_a;
};

int main(void)
{
    ZB b;
    std::cout << std::endl;
}
È stato utile?

Soluzione

Here is what happens:

  • ZB(0) is called but does not run

  • base constructor ZA(0) is called => "ZA (int n)0" and m_i = 1

  • initializers are processed in the order of fields declaration:

    • m_x(++m_i) is evaluated with ++1=2 => "ZA (int n)2" and m_i = 2

    • m_a(new ZA[2]) is evaluated and create the two ZA instances => "ZA (int n)0" twice

  • finally the ZB constructor is run => "ZB (int n)2"

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top