← कोर्स पर वापस जाएँ: Modern C++ from scratch

Polymorphism and virtual functions

वीडियो जल्द आ रहा है

Polymorphism means "many forms": being able to use objects of different classes through a common interface and having each one respond in its own way. Imagine a drawing program with circles, rectangles and triangles. You want a list of shapes and to traverse it calling area() without asking what type each one is. In C++ this is achieved with virtual functions: the call is resolved at run time according to the real type of the object, not the type of the pointer or reference you look at it through. It is the tool that makes inheritance truly useful.

virtual, override and the virtual destructor

In the base class you declare the function with virtual. In each derived class you rewrite it with the same signature and add override at the end: that way the compiler checks that you really override something, and warns you if you get a name or a const wrong. In addition, every base class meant to be used polymorphically must have a virtual destructor. Without it, deleting a derived object through a pointer to the base runs only the base destructor, leaving unreleased whatever the derived part reserved: undefined behavior. Writing virtual ~Shape() = default; costs one line and avoids this problem.

cpp
#include <iostream>
#include <string>
#include <vector>

class Shape {
public:
    virtual ~Shape() = default;
    virtual double area() const { return 0.0; }
    virtual std::string name() const { return "shape"; }
};

class Circle : public Shape {
public:
    explicit Circle(double radius) : radius_{radius} {}
    double area() const override { return 3.14159 * radius_ * radius_; }
    std::string name() const override { return "circle"; }

private:
    double radius_;
};

class Rect : public Shape {
public:
    Rect(double w, double h) : w_{w}, h_{h} {}
    double area() const override { return w_ * h_; }
    std::string name() const override { return "rect"; }

private:
    double w_;
    double h_;
};

void printInfo(const Shape& s) {   // works with any kind of Shape
    std::cout << s.name() << " area " << s.area() << '\n';
}

int main() {
    Circle c{2.0};
    Rect r{3.0, 4.0};

    std::vector<const Shape*> shapes{&c, &r};   // pointers to existing objects
    double total{0.0};
    for (const Shape* s : shapes) {
        printInfo(*s);
        total += s->area();
    }
    std::cout << "total " << total << '\n';
    // circle area 12.5664
    // rect area 12
    // total 24.5664
    return 0;
}

Slicing: the silent mistake

Polymorphism only works with pointers or references. If you copy a derived object into a variable of the base type by value, it gets "sliced": only the base part is copied and the rest is lost, along with the derived behavior. It is the most typical mistake of this lesson. That is why polymorphic functions take const Shape& and collections store pointers (ideally smart pointers, which you will see in week 7), never Shape objects by value. The compiler does not warn about slicing, so you must recognize it: if you see a vector<Shape> or a function taking Shape by value in a hierarchy, be suspicious.

cpp
#include <iostream>
#include <string>

class Animal {
public:
    virtual ~Animal() = default;
    virtual std::string sound() const { return "..."; }
};

class Dog : public Animal {
public:
    std::string sound() const override { return "woof"; }
};

void byValue(Animal a) {              // slicing: only the Animal part arrives
    std::cout << "by value: " << a.sound() << '\n';
}

void byReference(const Animal& a) {   // correct: the real type is preserved
    std::cout << "by reference: " << a.sound() << '\n';
}

int main() {
    Dog d;
    byValue(d);       // by value: ...
    byReference(d);   // by reference: woof
    return 0;
}

Each class with virtual functions internally keeps a table of pointers to its implementations (the vtable), and each object carries a hidden pointer to it. This adds a small memory cost and an indirection per call, which almost never matters. Use it when you truly need interchangeable behavior at run time. And remember: in constructors and destructors virtual calls do not reach derived classes, because that part of the object does not exist yet or has already been destroyed; avoid calling virtual functions from them.

✎ मेरे नोट्स

केवल इस ब्राउज़र में सहेजा गया। खाते में रखने के लिए साइन इन करें।0/5000 अक्षर

← पिछलाअगला →