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

原文链接: https://www.cnblogs.com/leetcode/p/3192594.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/96082

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月10日 上午3:29
下一篇 2023年2月10日 上午3:30

相关推荐