Inheritance
Inheritance
In C++, the single/simple inheritance is defined as the inheritance in which a derived class is
inherited from the only one base class.
// C++ program to demonstrate example of
// simple inheritance
#include <iostream>
using namespace std;
// Base Class
class A {
public:
void Afun(void);
};
// Function definiion
void A::Afun(void)
{
cout << "I'm the body of Afun()..." << endl;
}
// Derived Class
class B : public A {
public:
void Bfun(void);
};
// Function definition
void B::Bfun(void)
{
cout << "I'm the body of Bfun()..." << endl;
}
int main()
{
// Create object of derived class - class B
B objB;
return 0;
}
#include <iostream>
using namespace std;
// Base class
class std_basic_info {
private:
char name[30];
int age;
char gender;
public:
void getBasicInfo(void);
void putBasicInfo(void);
};
// function definitions
void std_basic_info::getBasicInfo(void)
{
cout << "Enter student's basic information:" << endl;
cout << "Name?: ";
cin >> name;
cout << "Age?: ";
cin >> age;
cout << "Gender?: ";
cin >> gender;
}
void std_basic_info::putBasicInfo(void)
{
cout << "Name: " << name << ",Age: " << age << ",Gender: " << gender <<
endl;
}
// Derived class
class std_result_info : public std_basic_info {
private:
int totalM;
float perc;
char grade;
public:
void getResultInfo(void);
void putResultInfo(void);
};
// Function definitions
void std_result_info::getResultInfo(void)
{
cout << "Enter student's result information:" << endl;
cout << "Total Marks?: ";
cin >> totalM;
perc = (float)((totalM * 100) / 500);
cout << "Grade?: ";
cin >> grade;
}
void std_result_info::putResultInfo(void)
{
cout << "Total Marks: " << totalM << ",Percentage: " << perc << ",Grade: "
<< grade << endl;
}
int main()
{
// Create object of derived class
std_result_info std;
return 0;
}
#include <iostream>
using namespace std;
public:
void get_a(int val_a)
{
a = val_a;
}
void disp_a(void)
{
cout << "Value of a: " << a << endl;
}
};
public:
// assign value of a from here
void get_b(int val_a, int val_b)
{
// assign value of a by calling function of class A
get_a(val_a);
b = val_b;
}
void disp_b(void)
{
// display value of a
disp_a();
cout << "Value of b: " << b << endl;
}
};
public:
// assign value of a from here
void get_c(int val_a, int val_b, int val_c)
{
// Multilevel Inheritance
// assign value of a, bby calling function of class B and Class A
// here Class A is inherited on Class B, and Class B in inherited on
Class B
get_b(val_a, val_b);
c = val_c;
}
void disp_c(void)
{
// display value of a and b using disp_b()
disp_b();
cout << "Value of c: " << c << endl;
}
};
int main()
{
// create object of final class, which is Class C
C objC;
return 0;
}