Single Inheritance

Single inheritance enables a derived class to inherit properties and behavior  from a single parent class. 
Example:        

Syntax
         class A
                {
                        -------
                        -------
                };
                class B : visibility_label A
                {
                        -------
                        -------
                };

Sample program
  
    class Shape
    {
        protected:
                float width, height;
        public:
                void set_data (float a, float b)
                {
                        width = a;
                        height = b;
                }
    };
    class Rectangle: public Shape
    {
        public:
                float area ()
                {
                        return (width * height);
                }
    };
    class Triangle: public Shape
    {
        public:
                float area ()
                {
                        return (width * height / 2);
                }
    };
    int main ()
    {
                Rectangle rect;
                Triangle tri;
                rect.set_data (5,3);
                tri.set_data (2,5);
                cout << rect.area() << endl;
                cout << tri.area() << endl;
                return 0;
    }
Output:
    15
     5

Advantages:
  • It allows a derived class to inherit the properties and behaviour of a base class, thus enabling code re-usability as well as adding new features to the existing code. This makes the code much more elegant and less repetitive.
  • Single inheritance is safer than multiple inheritance if it is approached in the right way. It also enables a derived class to call the parent class implementation for a specific method if this method is overridden in the derived class or the parent class constructor. 
Disadvantage:
  • In Inheritance, base class and child classes are tightly coupled. Hence If you change the code of parent class, it will affect all the child classes of it.
Single Inheritance Single Inheritance Reviewed by NEERAJ SRIVASTAVA on 3:57:00 PM Rating: 5

No comments:

Powered by Blogger.