Professional Documents
Culture Documents
Answer
* Single Inheritance
A (parent class) -> B (child class)
* Multiple Inheritance
A -> C, B -> C
* Hierarchical inheritance
A -> B, A -> C, A -> D
* Multilevel inheritance
A -> B, B -> C
* Hybrid inheritance
A -> B, A -> C, B -> D, C -> D
Class B
{
public:
int i;
};
class D : public B
{
public:
int j;
};
int main()
{
B B1;
D D1;
B1 = D1; //only i is copied to B1
}
The solution to that is that a Derived must have a using declaration of the hidden member
function OR redefine the hidden Base member function(s), even if they are non-virtual.
Normally this re-definition merely calls the hidden Base member function using the ::
syntax.
For example, a general class vehicle can be inherited by more specific classes car and
bike. The class vehicle is base class in this case.
class Base
{
int a;
public:
Base()
{
a = 1;
cout <<”inside Base class”;
}
};
class Derived:: public Base //class Derived is inheriting class Base publically
{
int b;
public:
Derived()
{
b = 1;
cout <<”inside Derived class”;
}
};
For example, a general class vehicle can be inherited by more specific classes car and
bike. The classes car and bike are derived classes in this case.
class vehicle
{
int fuel_cap;
public:
drive();
};
#include <iostream>
using namespace std;
class base
{
int i, j;
public:
void setij(int a, int b)
{
i = a;
j = b;
}
void showij()
{
cout <<”\nI:”<<i<<”\n J:”<<j;
}
};
int main()
{
derived ob;
//ob.setij(); // not allowed. Setij() is private member of derived
ob.setk(); //ok setk() is public member of derived
//ob.showij(); // not allowed. Showij() is private member of derived
ob.showall(); // ok showall() is public member of derived
return 0;
}
#include <iostream>
using namespace std;
class base
{
protected:
int i, j;
public:
void setij(int a, int b)
{
i = a;
j = b;
}
void showij()
{
cout <<”\nI:”<<i<<”\n J:<<j;
}
};
int main()
{
derived ob;
//ob.setij(); // not allowed. Setij() is protected member of derived
ob.setk(); //ok setk() is public member of derived
//ob.showij(); // not allowed. Showij() is protected member of derived
ob.showall(); // ok showall() is public member of derived
return 0;
}
In the above example all public members of Shape can be reused by the class Square. If
public key word is left, private inheritance takes place by default. If protected is specified
the inheritance is applied for any descendant or friend class.
class Base1
{
private:
int no1;
public:
void show1()
{
cout << “The no is:” << no1 <<”\n”;
}
};
class Base2
{
private:
int no2;
public:
void show2()
{
cout << “The no is:” << no2 <<”\n”;
}
};
class Derived: public Base1, public Base2 //Multiple inheritance
{
public:
void set(int x, int y)
{
no1 = x; no2 = y;
}
};
int main()
{
Derived ob;
ob.set(10, 20);
ob.show1(); // Derived class obj can access member functions of both base classes
ob2.show2(); //Derived class obj can access member functions of both base class
return 0;
}
More Questions: