Having the following class hierarchy, what will be printed out as a result of the program execution?
#include <iostream>

using namespace std;

class Aggregated{

  public:

      Aggregated(){
        cout<<"Aggregated construct"<<endl;
      }

      ~Aggregated(){
        cout<<"Aggregated destruct"<<endl;
      }
};

class Base{

  protected:

      Aggregated * ptr;

  public:

      Base():ptr(NULL){
       cout<<"Base construct"<<endl;
       f();
      }

      virtual ~Base()=0;

      virtual void f()=0;
};

Base::~Base(){
        if(ptr)
            delete ptr;
        cout<<"Base destruct"<<endl;
}

void Base::f(){
   cout<<"Base f"<<endl;
}

class Derived: public Base{

  public:

      Derived(){
        if(!ptr)
            ptr = new Aggregated;

        cout<<"Derived construct"<<endl;
      }

      ~Derived(){
        cout<<"Derived destruct"<<endl; 
      }

      void f(){}
};

int main(){

    Base* b = new Derived();

    delete b;

    cin.get();

    return 0;
}

Agree with prorokvspsix79. To call function f of class Base which is declared as pure virtual but has definition Base::f();

2023 Nov 11, 10:57:36 PM

Iso C++ 2011 10.4 $6 Member functions can be called from a constructor (or destructor) of an abstract class; the effect of making a virtual call (10.3) to a pure virtual function directly or indirectly for the object being created (or destroyed) from such a constructor (or destructor) is undefined.

2023 Jul 30, 7:19:46 PM

DileriumL - my compilers show some warnings about running pure virtual, but run it successfully, since this pure virtual has a defined body. I checked it on few compilers

2022 Oct 15, 8:45:35 PM

There is actually runtime error. You can't call pure virtual function in constructor. Fix this, please

2022 Aug 23, 7:40:08 PM

Следи за CodeGalaxy

Мобильное приложение Beta

Get it on Google Play
Обратная Связь
Cosmo
Зарегистрируйся сейчас
или Подпишись на будущие тесты