๐งโโ๏ธ 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;
}
};
publicinheritance: โ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
Point2Dreference holds aPoint3Dobject, 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 Case | Inheritance? |
|---|---|
| You need multiple related types that behave differently | Yes |
| You want to generalize with base class pointers or references | Yes |
| Youโre sharing behavior across unrelated classes | No, use composition/templates |
| You donโt want to deal with destructor landmines | Use smart pointers, queen |