Book has-a cost;
Inheritance expresses the is-a relationship.
point3d is-a point.
Inheritance allows us to abstract some parts of the data to hide them from the programmer, while allowing re-use of other parts.
For example, a product consists of one or more programs. Programs consist of one or more code units.
Products have data members like release dates, cost, part numbers, manuals, owner, completion date, etc. They have methods like is_development_complete() and get_part_number();
Programs have data members owners, language, compiler, completion date. They have methods like is_development_complete() and compile_program();
Code units have data members owners, language compilers, unit test date, completion date, NCSL. They have methods like is_development_complete() and compile_program() and count_ncsl().
You can see that there are commonalities and differences.
A simpler example is a class point.
class point { public: point() { x = y = 0;}; point(const int a, const int b) { x = a; y = b ;}; point(const point from&) { x = from.x; y = from.y ;}; void setx(const int val) { x=val;}; void sety(const int val) { y=val;}; int gety(){return x;}; int getx(){return x;}; private: int x,y; };To make a 3D point, we want to start with a point and extend it, rather than start from scratch. We want to use the x,y coordinates from point and add a z. In C++, the syntax is :
class point3d : public point { public: point3d() {setx(0);sety(0);z=0;}; point3d(const int a,const int b,const int c) {setx(a);sety(b);z=c;}; int getz() {return z;}; void setz(const int a) {z = a;}; private: int z; };Note the public before point. C++ defaults to private access to the superclass, which means we don't have access to the private members of the superclass. there are two kinds of inheritance access.
private | public | |
private | private | private |
protected | private | protected |
public | private | public |
point3d(1,2,3);before the 3 arg constructor is executed, the no arg constructor for point is run. Then the calls to setx() and sety() override the initialization. This is a little redundant. so we can define the subclass constructor to use the parameterized superclass constructor.
point3d(const int a,const int b, const int c) : point(a,b) { z=c; }If there were more superclasses, make a comma separated list. This can be used to initialize variables by calling a constructor.
point() : x(0),y(0) {}; point( const int a,const int b) : x(a),y(b) {};