class Base {
public:
Base() {
Init(); /*this will invoke the base function, because derived object is not been created yet.*/
}
virtual ~Base() = default;
virtual void Init() { cout << "Base init\n"; }
void Run() { Work(); /*this will invoke the derived override function*/ }
virtual void Work() { cout << "Base work\n"; }
};
class Derived : public Base {
public:
Derived() : Base() { Init(); }
~Derived() override = default;
void Init() override { cout << "Derived init\n"; }
void Work() override { cout << "Derived Work\n"; }
};
int main(int argc, char** argv) {
std::unique_ptr<Base> derived = std::make_unique<Derived>();
derived->Run();
/* Output:
Base init
Derived init
Derived Work
*/
return 0;
}
Inheritance and Polymorphism in cpp
最新推荐文章于 2024-09-15 11:40:06 发布