C++ Programming Tutorial

Learn modern C++ step-by-step with concise explanations and practical examples. Navigate topics from basics to advanced features using the sidebar.

Inheritance and Polymorphism

Inheritance lets a derived class reuse and extend a base class. Virtual functions enable dynamic dispatch (polymorphism) so the correct method runs based on the actual type.

Virtual Functions
#include \n\nclass Base {\npublic:\n    virtual void speak() { std::cout << "Base"; }\n    virtual ~Base() = default;\n};\n\nclass Derived : public Base {\npublic:\n    void speak() override { std::cout << "Derived"; }\n};\n\nint main(){\n    Base* b = new Derived();\n    b->speak(); // prints "Derived"\n    delete b;\n}
Notes
  • Mark base destructors `virtual` when deleting through base pointers.
  • Use `override` in derived methods to catch signature mismatches.

Keep Practicing

Use the online compiler to run examples and test variations. Reinforce learning by building small programs for each topic.