๐Ÿง™โ€โ™€๏ธ C++ Class Inheritance & Polymorphism โ€“ With a 3D Geometry Twist

๐Ÿงฑ Base Class โ€“ Point2D

class Point2D {
protected:
    float x, y;

public:
    Point2D(float x = 0, float y = 0) : x(x), y(y) {}

    virtual void print() const {
        std::cout << "Point2D(" << x << ", " << y << ")" << std::endl;
    }

    virtual ~Point2D() {} // Always virtual destructor for polymorphic base
};
  • protected: accessible to subclasses, but hidden from the outside world like a locked diary.
  • virtual: magic keyword that enables polymorphism (late binding).
  • Destructor is virtual so your objects donโ€™t leave memory corpses behind. ๐Ÿ‘ป

๐ŸŒŒ Subclass โ€“ Point3D

class Point3D : public Point2D {
    float z;

public:
    Point3D(float x = 0, float y = 0, float z = 0) : Point2D(x, y), z(z) {}

    void print() const override {
        std::cout << "Point3D(" << x << ", " << y << ", " << z << ")" << std::endl;
    }
};
  • public inheritance: โ€œyes, Iโ€™m extending the public interface, not hiding it.โ€
  • override: optional, but makes the compiler scream if you mess up a virtual override (bless her).

๐Ÿงช Polymorphism in Action

void describePoint(const Point2D& p) {
    p.print();
}

int main() {
    Point2D p2(1, 2);
    Point3D p3(3, 4, 5);

    describePoint(p2); // prints Point2D(1, 2)
    describePoint(p3); // prints Point3D(3, 4, 5) โ€“ polymorphism magic!
}
  • This is the power move: a Point2D reference holds a Point3D object, but still calls the right method.
  • No casting. No mess. Just vibes. ๐ŸŽฉโœจ

๐Ÿ’€ What If You Forget virtual?

If you remove virtual from Point2D::print(), then the method wonโ€™t get overridden at runtime โ€” youโ€™ll always call the base version. This is what we call... a tragic plot twist.


๐Ÿ”ฎ When to Use This

Use CaseInheritance?
You need multiple related types that behave differentlyYes
You want to generalize with base class pointers or referencesYes
Youโ€™re sharing behavior across unrelated classesNo, use composition/templates
You donโ€™t want to deal with destructor landminesUse smart pointers, queen