Inheritance enables classes to use the properties of other classes and add to those properties.
The thing to remember about object programming is that it attempts to create a software model as close to the real world as possible. Inheritance forms an important role to meet this need. Take the following example.
A fabric can have a colour and size and it is also used to make clothes as well as tents. Now looking at this from the other angle tents are made from fabric and poles but clothes are made from fabric and buttons. So, Tents and clothes have something in common, If we described tents and clothes in C++, we can seperate fabric into a seperate class that the Tent and Clothes classes can inherit.
----------- | Fabric | ----------- A A | | --- --- | | --------- ----------- | Tent | | Clothes | --------- ----------- |
Now for some buzz words:
// ... The base class 'Fabric' // ... is no different to normal. |
class Fabric { public: Fabric() {}; ~Fabric() {}; SetSize(int x, int y) { Length = x; Width = y; }; SetColour(char *C) { strcpy(Colour, C); } private: int Length; int Width; char Colour[20]; }; |
// ... The derived class 'Tent' // ... names 'Fabric' as a base class. |
// ... The derived class 'Clothes' also // ... names 'Fabric' as a base class. |
class Tent : public Fabric { public: Tent() {}; ~Tent() {}; SetNumOfPoles(int P) { Poles = P; }; private: int Poles; }; |
class Clothes : public Fabric { public: Clothes() {}; ~Clothes() {}; SetNumOfButtons(int B) { Buttons = B; }; private: int Buttons; }; |
What we now have are three classes with the following public methods.
Consider this piece of code.
void Init(Fabric &Material); main() { Tent Frame; Clothes Jacket; Init(Frame); Init(Jacket); } void Init(Fabric &Material) { Material.SetColour("Red"); Material.SetSize (10, 20); } |
The function 'Init' expects an object of type 'Fabric' but we are passing objects of type 'Tents' and 'Clothes', this is OK as 'Tents' and 'Clothes' are derived from Fabric.
Top | Master Index | Keywords | Functions |