construct and destruct and virtual

#include <iostream>
using namespace std;
 class   A
  {
  public:

  A();
  ~A();

  };
  A::A()
  {
      cout<<"A star"<<endl;
  }

  A::~A()
  {

  cout<<"Delete   class   AP/n"<<endl;

  }
  class   B   :   public   A
  {
  public:
  B();
          ~B();

  };

  B::B()
  {
      cout<<"B star"<<endl;
  }

  B::~B()
  {
  cout<<"Delete   class   BP/n"<<endl;
  }
  int   main(int   argc,   char*   argv[])
  {
      A  *a = new B;
      delete a;

  //A   *b=new   B;
  //delete   b;
            return   0;

  }
A star
B star
Delete   class   AP/n
因此,在创建子类对象时,为了初始化从父类继承来的数据成员,系统需要调用其父类的构造方法。

 

这个时候需要加一个   virtual  ~A()

A star
B star
Delete   class   BP/n
Delete   class   AP/n

需要注意的是 要有delete 不然析构函数不会被调用

 a virtual function or virtual method is a function or method whose behavior can be overridden within an inheriting class by a function with the same signature. This concept is a very important part of the polymorphism portion of object-oriented programming (OOP).

 

"A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class that is not abstract" - Wikipedia

So, the virtual function can be overriden and the pure virtual must be implemented.

 

//============================================================================
// Name        : test.cpp
// Author      :
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
using namespace std;
 class   A
  {
  public:

  A();
  virtual ~A();

  };
  A::A()
  {
      cout<<"A star"<<endl;
  }

  A::~A()
  {

  cout<<"Delete   class   AP/n"<<endl;

  }
  class   B   :   public   A
  {
  public:
  B();
          ~B();

  };

  B::B()
  {
      cout<<"B star"<<endl;
  }

  B::~B()
  {
  cout<<"Delete   class   BP/n"<<endl;
  }
  int   main(int   argc,   char*   argv[])
  {
      B  *a = new B;
      delete a;

  //A   *b=new   B;
  //delete   b;
            return   0;

  }
A star
B star
Delete   class   BP/n
Delete   class   AP/n

 

posted on 2013-07-16 08:41  brave_bo  阅读(212)  评论(0)    收藏  举报

导航