Multiple Inheritance With Example Program and Syntax

Explain Multiple Inheritance With Example Program and Syntax







Multiple inheritances: - Multiple-inheritance is a mechanism of deriving a new class from two or more base classes. In multiple-inheritance there will be only one derived class and more than one base class’s.
Multiple-inheritance allows us to combine the feature of several existing classes for defining new classes. The syntax of a derived class with multiple base classes is as follows.

        Class D: Visiblity B-1, Visibility B-2...

Using comma operator to separate the base classes, Suppose if you create an object of a derived class then first it call the constructor of class B-1 and then call constructor of class B-2 then call the constructor of derived class. Similarly the first the destructor of the derived class is called and then call the destructor of the class B-2 and then call destructor of class B-1 to destroy the object of the derived class. The order of calling is always depend on the order of derivation. Suppose if a base class is derived as virtual then at first the virtual class constructor is called then call the remaining class constructor declared in the order

        class m
        {
        protected : int m;
        public : void get m( )
        { cout<<“enter m value “;
          cin>>m;
        }
        };

        class N
        {
        protected: int n;
        public : void getn( )
        { cout<<“enter n value”;
          cin>>n;
        }
};
       class P: public M, public N
        {
        public : void display ( )
        { cout<<“m=”<<m endl;
          cout<<“n=”<<n<< endl;
          cout<<“mxn=”<<m*n<<endl;
        }
        };
       void main( )
       {
        P p;
        p.getm( );
        p.getn();
        p. display( );
        getch( );
        }


        input of the above program;
        enter m value = 20
        enter n value =10


        output of the above program m=20
                                                      n=10
                                                      m*n=200

Labels: