Problem with tracing code

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?

Can anyone help?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
using namespace 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;
}
Hi,

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.

http://www.cplusplus.com/doc/tutorial/classes/

http://en.cppreference.com/w/cpp/language/direct_initialization
http://en.cppreference.com/w/cpp/language/initializer_list


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.
Last edited on
Topic archived. No new replies allowed.