Multiple Inheritance in C++
#include<iostream.h>
#include<conio.h>
class A
{
public:
int x;
void getx()
{
cout << "enter value of x: "; cin >> x;
}
};
class B
{
public:
int y;
void gety()
{
cout << "enter value of y: "; cin >> y;
}
};
class C : public A, public B //C is derived from class A and class B
{
public:
void sum()
{
cout << "Sum = " << x + y;
}
};
int main()
{
C obj1; //object of derived class C
obj1.getx();
obj1.gety();
obj1.sum();
return 0;
}
Expected Output:-
enter value of x: 5
enter value of y: 4
Sum = 9
//Implementation of Multiple Inheritance.
#include<iostream.h>
#include<conio.h>
class Mammal {public:
Mammal()
{
cout << "Mammals can give direct birth." << endl;
}
};
class WingedAnimal {
public:
WingedAnimal()
{
cout << "Winged animal can flap." << endl;
}
};
class Bat: public Mammal, public WingedAnimal {
};
int main()
{
Bat b1;
return 0;
}
Expected Output:-
Mammals can give direct birth.
Winged animal can flap.
//More Example.
#include <iostream.h>
#include <conio.h>
class A
{
protected:
int a;
public:
void get_a(int n)
{
a = n;
}
};
class B
{
protected:
int b;
public:
void get_b(int n)
{
b = n;
}
};
class C : public A,public B
{
public:
void display()
{
std::cout << "The value of a is : " <<a<< std::endl;
std::cout << "The value of b is : " <<b<< std::endl;
cout<<"Addition of a and b is : "<<a+b;
}
};
int main()
{
C c;
c.get_a(10);
c.get_b(20);
c.display();
return 0;
}
Expected Output:-
The value of a is : 10
The value of b is : 20
Addition of a and b is : 30
//More Example..
#include<iostream.h>
#include<conio.h>
class A
{
public:
void display()
{
std::cout << "Class A" << std::endl;
}
};
class B
{
public:
void display()
{
std::cout << "Class B" << std::endl;
}
};
class C : public A, public B
{
void view()
{
display();
}
};
int main()
{
C c;
c.display();
return 0;
}
Output:
error: reference to 'display' is ambiguous
display();
//More Example..
#include<iostream.h>
#include<conio.h>
class student
{
protected:
int rno,m1,m2;
public:
void get()
{
cout<<"Enter the Roll no :";
cin>>rno;
cout<<"Enter the two marks :";
cin>>m1>>m2;
}
};
class sports
{
protected:
int sm; // sm = Sports mark
public:
void getsm()
{
cout<<"\nEnter the sports mark :";
cin>>sm;
}
};
class statement:public student,public sports
{
int tot,avg;
public:
void display()
{
tot=(m1+m2+sm);
avg=tot/3;
cout<<"\n\n\tRoll No : "<<rno<<"\n\tTotal : "<<tot;
cout<<"\n\tAverage : "<<avg;
}
};
void main()
{
clrscr();
statement obj;
obj.get();
obj.getsm();
obj.display();
getch();
}
Tags:
er. manjeet singh
manjeet singh kuthar
Multiple Inheritance in c++
Multiple Inheritance in cpp
www.mskuthar.blogspot.com