Is the Wikipedia example at this article about method overiding in C++ correct?
Please see the code below where I have mentioned a comment //INCORRECT
Slightly confused about overiding in C++ and run time polymorphism. What should this cast do?
#include <iostream>
class Rectangle {
public:
explicit Rectangle(double l, double w) : length(l), width(w) {}
virtual void print() const;
private:
double length;
double width;
};
void Rectangle::print() const { // print() method of base class
std::cout << "Length = " << this->length << "; Width = " << this->width;
}
class Box : public Rectangle {
public:
explicit Box(double l, double w, double h) : Rectangle(l, w), height(h) {}
virtual void print() const; // virtual is optional here, but it is a good practice to remind it to the developer
private:
double height;
};
void Box::print() const { // print() method of derived class
Rectangle::print(); // Invoke parent print() method.
std::cout << "; Height= " << this->height;
}
int main(int argc, char** argv) {
Rectangle rectangle(5.0, 3.0); rectangle.print();
// outputs:
// Length = 5.0; Width = 3.0
Box box(6.0, 5.0, 4.0);
// the pointer to the most overridden method in the vtable in on Box::print
//box.print(); // but this call does not illustrate overriding
static_cast<Rectangle&>(box).print(); // this one does
// outputs:
// Length = 5.0; Width = 3.0; Height= 4 // INCORRECT
//But it actually outputs Length = 6; Width = 5; Height = 4
getchar();
return 0;
}
this line:
static_cast<Rectangle&>(box).print();has same effect as this code would have:and also same effect as this code would have:
It means that Box object was created (
Box box(6.0, 5.0, 4.0);= in runtime you seeBox) and it doesn’t matter what is the type of pointer / reference where you store this object. The fact that you store box as aRectangle*is what you see in compile time.Most important fact about overriding virtual methods is that about “which method will be called?” is decided in runtime.
Hope this helps.