How would you use inheritance in an objectoriented program Y
How would you use inheritance in an object-oriented program? You can use the example you provided in the Implementing Inheritance thread as a reference. Discuss when a program might use both the base class and the derived class and why.
Solution
Answer:-
Inheritance :-
creating a new class using the inheritance property. It is possible to derive one class from another or even several (Multiple inheritance), like a tree we can call base class to the root and child class to any leaf; in any other case the parent/child relation will exist for each class derived from another.
Base Class :
A base class is a class that is created with the intention of deriving other classes from it.
Child Class:
A child class is a class that was derived from another, that will now be the parent class to it.
Parent Class:
A parent class is the closest class that we derived from to create the one we are referencing as the child class.
Program:-
#include <iostream>
using namespace std;
class Person
{
public:
string profession;
int age;
Person(): profession(\"unemployed\"), age(16) { }
void display()
{
cout << \"My profession is: \" << profession << endl;
cout << \"My age is: \" << age << endl;
walk();
talk();
}
void walk() { cout << \"I can walk.\" << endl; }
void talk() { cout << \"I can talk.\" << endl; }
};
// MathsTeacher class is derived from base class Person.
class MathsTeacher : public Person
{
public:
void teachMaths() { cout << \"I can teach Maths.\" << endl; }
};
// Footballer class is derived from base class Person.
class Footballer : public Person
{
public:
void playFootball() { cout << \"I can play Football.\" << endl; }
};
int main()
{
MathsTeacher teacher;
teacher.profession = \"Teacher\";
teacher.age = 23;
teacher.display();
teacher.teachMaths();
Footballer footballer;
footballer.profession = \"Footballer\";
footballer.age = 19;
footballer.display();
footballer.playFootball();
return 0;
}

