Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- class Base
- {
- public:
- Base()
- {
- cout <<"constructor base\n";
- }
- virtual ~Base()
- {
- cout <<"Destructor base \n";
- }
- };
- class Derived:public Base
- {
- public:
- Derived()
- {
- cout <<"constructor Derived\n";
- }
- ~Derived() override
- {
- cout <<"Destructor Derived\n";
- }
- };
- int main()
- {
- Base * base = new Base();
- delete base;
- cout <<"---------------"<<endl;
- Derived *derived = new Derived();
- delete derived;
- cout <<"---------------"<<endl;
- Base* poly = new Derived();
- //注意当析构函数前面不加virtual keyword,析构时的第三种情况
- delete poly;
- return 0;
- /**
- * output: base class 析构函数不加virtual
- constructor base
- Destructor base
- ---------------
- constructor base
- constructor Derived
- Destructor Derived
- Destructor base
- ---------------
- constructor base
- constructor Derived
- Destructor base
- *
- */
- }
Add Comment
Please, Sign In to add comment