| Topic: C++-Language Inheritance One reason to use inheritance is that it permits you to reuse code from a previous project, but gives you the flexibility to slightly modify it if the old code doesn't do exactly what you need for the new project. It doesn't make sense to start every new project from scratch since some code will certainly be repeated in several programs and you should strive to build on what you did previously. However, it is easy to make an error if you try to modify the original class. You are less likely to make an error if you leave the original alone and only add to it. Another reason for using inheritance is if the project requires the use of several classes which are very similar but slightly different. In this chapter we will concentrate on the mechanism of inheritance and how to build it into a program. A better illustration of why you would use inheritance will be given in later chapters where we will discuss some practical applications of object oriented programming. The principle of inheritance is available with several modern programming languages and is handled slightly differently with each. C++ allows you to inherit all or part of the members and methods of a class, modify some, and add new ones not available in the parent class. You have complete flexibility, and as usual, the method used with C++ has been selected to result in the most efficient code execution. These existing classes are called as base classes. The derived Inheritance permits code reusability. This is one important use Once a base class is written and debugged it need not be touched Inheritance can also help in the original conceptualization of a ** Some important points that have to be noted about inheritance are 1. A derived class inherits all the capabilities of the base class, but 2. protected members behave just like private members until a new 3. If a base class has private members those members are not 4. A derived class can specify that a base class is public or private class c : public b ; Example // derived classes#include <iostream.h> class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b ;} }; class CRectangle: public CPolygon { public: int area (void) { return (width * height); } }; class CTriangle: public CPolygon { public: int area (void) { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; rect.set_values (4,5); trgl.set_values (4,5); cout << rect.area() << endl; cout << trgl.area() << endl; return 0; }
|
|