[inheritance] Quick refresher (1)
[inheritance] Quick refresher (1)
Base class
Derived class
// Base class
class Shape
public
void setWidth(int w) { width = w;
void setHeight(int h) { height = h; }
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape
public:
int getArea() { return (width * height); }
};
int main(void)
Rectangle Rect;
return 0;
}
Output: Total area: 35
Multiple Inheritance
A class can inherit members from more than one class, here is the extended syntax:
class Derived-class access-specifier Base-class A, access-specifier Base-class B,
Access specifier is public, protected, or private and it is given for every base class.
Example:
#include <iostream>
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape, public PaintCost {
public:
int getArea() { return (width * height); }
};
int main()
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
return 0;
}
Output: Total area: 35
Total paint cost: $2450
Function overriding
If needed, a derived class can redefine an inherited member function.
If the derived class defines a member function which has the same signature (name,
number and type of parameters) as the base class, then the derived class is
overriding this inherited member function.
Reference: https://www.tutorialspoint.com/cplusplus/