CHAPTER 15

image

Overriding

A new method in a derived class can redefine a method in a base class in order to give it a new implementation.

Hiding derived members

In the example below, Rectangle’s getArea method is redeclared in Triangle with the same signature. The signature includes the name, parameter list and return type of the method.

class Rectangle{ public:  int x, y;  int getArea() { return x * y; }};class Triangle : public Rectangle{ public:  Triangle(int a, int b) { x = a; y = b; }  int getArea() { return x * y / 2; }};

If a Triangle object is created and the getArea method is invoked, then Triangle’s version of the method will get called. ...

Get C++ Quick Syntax Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.