Could any one give me an example of this?

In C++ primer:
While a constructor or destructor is running, the object is incomplete. To accommodate this incompleteness, the compiler treats the object as if its type changes during construction or destruction. Inside a base-class constructor or destructor, a derived object is treated as if it were an object of the base type.
The type of an object during construction and destruction affects the binding of virtual functions.
If a virtual is called from inside a constructor or destructor, then the version that is run is the one defined for the type of the constructor or destructor itself. (I could not imagine the usage of this, could anyone give me an example? thanks a lot)
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
class Parent
{
public:
  virtual void Print()
  {
    cout << "Parent" << endl;
  }

  Parent()
  {
    Print();
  }

  ~Parent()
  {
    Print();
  }
};

class Child : public Parent
{
public:
  virtual void Print()
  {
    cout << "Child" << endl;
  }
};


int main()
{
  Parent* ptr = new Child;  // prints "Parent", not "Child" like you might expect
  ptr->Print();  // prints "Child"
  delete ptr;  // prints "Parent"
}
Topic archived. No new replies allowed.