construct and destruct and virtual

本文探讨了C++中类继承与虚拟析构函数的使用,解释了构造和析构过程,并通过示例代码说明了如何正确地初始化继承自父类的数据成员。
#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值