norman's blog

Notes of an amnesiac.
Never stop thinking.
Find an aesthetic description.

Tuesday, June 30, 2009

Constructors and destructors of an class and its member which is also a class

The compiler will call the member's constructor just before the class's constructor, and call the member's destructor just behind the class's constructor. That is because the class's constructor and destructor may access the member, which is supposed to be allocated. See code example:
class B {
  public:
    B();
    ~B();
};
B::B() {
  printf("construct B\n");
}
B::~B() {
  printf("destruct B\n");
}

class A {
  public:
    A();
    ~A();
  private:
    B b;
};
A::A() {
  printf("construct A\n");
}
A::~A() {
  printf("destruct A\n");
}



int main() {

  printf("a live\n");
  {
  A a;
  }
  printf("a die\n");
}
The result is:
a live
construct B
construct A
destruct A
destruct B
a die
An alternative method is use the pointer and new&delete. new and delete will call the constructor and destructor respectively, in the case that the pointer point to a class type.
class B {
  public:
    B();
    ~B();
};
B::B() {
  printf("construct B\n");
}
B::~B() {
  printf("destruct B\n");
}

class A {
  public:
    A();
    ~A();
  private:
    B * b;
};
A::A() {
  printf("construct A\n");
  b = 0; //b is random value at first, assigning it to 0 avoid some error if new failed 
  b = new B;
}
A::~A() {
  printf("destruct A\n");
  if(b)
    delete(b);
}



int main() {

  printf("a live\n");
  {
  A a;
  }
  printf("a die\n");
}
The result is:
a live
construct A
construct B
destruct A
destruct B
a die

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home