Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Multiple Inheritance in C++

    • 0
    • 4
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 186
    Comment on it

    C++ supports multiple inheritance unlike java. In multiple inheritance a class in C++ can have more than one class as it's parent class i.e., it can inherit property from more than one class.

                class Area        class Perimeter
                    |                   |
                    ---------------------
                             |
                      class Square
    

    For example :

    class Area
    {
    public:
        int area(int a)
        {
            return a*a;
        }
    };
    
    class Perimeter
    {
    public:
        int peri(int a)
        {
            return 4*a;
        }
    };
    
    class Square : private Area, private Perimeter
    {
        private:
            int a;
        public:
           void get_data( )
           {
               cout<<"Enter length: ";
               cin>>a;
           }
    
           int area()
           {
                     return Area::area(a);
           }
    
           int peri()
           {
           return Perimeter::peri(area);
           }
    };
    
    int main()
    {
        Square s;
        s.get_data();
        cout<<"Area = "<<s.area();
        cout<<"Perimeter = "<<s.peri();
        return 0;
    }
    

    OUTPUT :

    Enter length: 5
    Area = 25
    Perimeter = 20
    

    Note :Using multiple inheritance sometime leads the problem of ambiguity. For eg:

     
    class A { virtual void add(); };
    class B { virtual void add(); };
    class C : public A ,public B { void add(); };
    
    This issue can be solved by using explicit qualification. We explicitly say to the compiler where to get the function that we need to call:
     
    C c;
    c.add();
    A::add();  //this calls function of class A
    B::add();  //this calls function of class B
     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: