close
Inheritance constructor & destructor :
#1. Constructor
#include <iostream> using namespace std; class base { public: base(int x, int y) { this->x = x, this->y = y; } ~base() {} int x; int y; }; class basePlus : public base { public: basePlus(int x, int y, int z) : base(x, y) { this->z = z; } ~basePlus() {} int z; }; int main() { basePlus* bp = new basePlus(1,2,3); cout << "x : " << bp->x << "\n"; cout << "y : " << bp->y << "\n"; cout << "z : " << bp->z << "\n"; delete bp; return 0; }
Output
x : 1 y : 2 z : 3
#2. Destructor
(a) without virtual
#include <iostream> using namespace std; class base { public: base(int x, int y) { this->x = x, this->y = y; } ~base() { cout << "base destructor\n"; } int x; int y; }; class basePlus : public base { public: basePlus(int x, int y, int z) : base(x, y) { this->z = z; } ~basePlus() { cout << "basePlus destructor\n"; } int z; }; int main() { basePlus* bp = new basePlus(1,2,3); base* b = bp; delete b; return 0; }
Output
base destructor
(b) with virtual
#include <iostream> using namespace std; class base { public: base(int x, int y) { this->x = x, this->y = y; } virtual ~base() { cout << "base destructor\n"; } int x; int y; }; class basePlus : public base { public: basePlus(int x, int y, int z) : base(x, y) { this->z = z; } ~basePlus() { cout << "basePlus destructor\n"; } int z; }; int main() { basePlus* bp = new basePlus(1,2,3); base* b = bp; delete b; return 0; }
Output
basePlus destructor base destructor
文章標籤
全站熱搜