Through a base-class reference, a virtual call runs the derived version; a non-virtual call does not.
C++ · beginner · 8 min · 13 steps · free
#include <iostream>
using namespace std;
class Shape {
public:
virtual double area() const { return 0; }
double plain() const { return -1; } // not virtual
virtual ~Shape() {}
};
class Square : public Shape {
double s;
public:
Square(double s) : s(s) {}
double area() const override { return s * s; }
double plain() const { return 99; }
};
int main() {
Square sq(3);
Shape &ref = sq;
double a = ref.area(); // virtual: Square's version runs
double p = ref.plain(); // not virtual: Shape's version runs
cout << a << " " << p << endl;
return 0;
}Square constructor to set up the new object, with s = 3.Shape constructor to set up the new object.Square() has finished, so its variables are gone. Shape() has finished, so its variables are gone. sq is created on the stack with the value {s: 3}.area() has finished, so its variables are gone. The value it returned, 9, is stored in a.plain() has finished, so its variables are gone. The value it returned, -1, is stored in p.9 -1.0.~Square() runs, because the object is going away.~Shape() runs, because the object is going away.Answer: Derived::f. Dynamic dispatch.
Answer: So deleting through a base pointer cleans up the derived part. Otherwise only the base destructor runs.
← Inheritance · Abstract Classes and Pure Virtual Functions →