Inheritance Intro
A class can inherit another. This means that all members of the inherited class
(base class) will become members of the inheriting class (derived class).
Given a class
ClassA, a class
ClassB can be defined, inheriting
ClassA:
class ClassA{};
class ClassB: public ClassA {};
The keyword
public means that all
accessibility levels for
ClassA members will
be maintained in
ClassB, i. e. a public member
remains public, so does a protected or a private one.
In the program below a class
Person is
declared, then a class
Teacher, derived from
Person, is declared.
All members of
Person become members of
Teacher. A
Teacher
object will contain
name,
age,
setNameAge().
Further, it will contain
subject and
setSubject().
class Teacher : public Person ensures that:
all public members of
Person will be public in
Teacher,
all protected members of
Person will be
protected in
Teacher,
all private members of
Person will be private
in
Teacher.
Basically it keeps the privacy level of the inherited class members the same as
it was in the base class.
If the derived class were defined as:
class Teacher: protected Person
all public base class members would become protected in the derived class.
If the derived class were defined as:
class Teacher: private Person
all public and protected base class members would become private in the derived class.
Example
#include <iostream>
#include <string<
using namespace std;
class Person
{
string name; // by default all class members are private
int age;
public: // the following members are public
void setNameAge(string aName, int anAge)
{
name = aName;
age = anAge;
}
void printNameAge()
{
cout << "name: " << name << " age: " << age << "\n";
}
};
class Teacher : public Person
{
string subject;
public:
void setSubject(string aSubject)
{
subject = aSubject;
}
void printSubject()
{
cout << "subject: " << subject;
}
};
int main()
{
Person person1;
person1.setNameAge("John" , 23);
Teacher teacher1;
teacher1.setNameAge("Frank", 78);
teacher1.setSubject("Math");
person1.printNameAge();
teacher1.printNameAge();
teacher1.printSubject();
}
Output
name: John age: 23
name: Frank age: 78
subject: Math