Hi! I've problem understanding this code, I thought m is a variable? But in class A it seems to be a function? And the main class calls only object of type B, but the output I got includes stuff from class A, and it seems like the code is run multiple times, but I don't see any while/for loop?
#include <iostream>
usingnamespace std;
class A
{
public:
A(int n = 7) : m(n) {
cout << "A() n = " << n
<< " m = " << m << endl;
}
~A() { cout << "~A() m = " << m << endl; }
protected:
int m;
};
class B : public A
{
public:
B(int n) : x(m + 1) , y(n) {
cout << "B() n = " << n << endl;
}
public:
~B() {
cout << "~B() m = " << m << endl;
--m;
}
private:
A x;
A y;
};
int main()
{
B b(10);
return 0;
}
On line 12 m is an int. You may be confused by it being a function because of the direct initialisation in the member initialisation list on line 6. Btw, public or protected data in a class is a bad idea, make data members private, then provide an interface of functions.
And the main class calls only object of type B, but the output I got includes stuff from class A
When an object of type B is created, the constructor of type A is called first , then B ctor. When things are destroyed, the destructors are called in reverse order - B then A.
Edit:
B has 2 members of type A, so A's ctor is called for those as well.