What will be printed out as a result of the following code execution?
#include <iostream>
using namespace std;

class a
{
public:
  static int s;
  a(){++s; cout<<s;}
  ~a(){--s;cout<<s;}
};

int a::s;

class b:public a
{
public:
  b():a(){++s;cout<<s;}
  ~b(){--s;cout<<s;}
};


int main()
{
  a *one = new b;
  delete one;
  cin.get();
}
Explanation
Let's consider order of constructors execution. Constructor A() wiil be called first which make variable s equal to 1, then executes B(), which is make s = 2. When we delete pointer "one", destructor of class B executes, s = 1 and output 1. But destructor ~A() isn't declared as virtual, hence it will not execute..

... Since destructor ~A() isn't declared as virtual and type of pointer "one" is A, when we delete pointer "one", only destructor of class A executes, s = 1 and output 1. Destructor of class B will not execute..

2023 Nov 10, 1:54:28 PM

Слідкуй за CodeGalaxy

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

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