Inheritance In C

Introduction

Inheritance involves creating new objects by directly acquiring the attributes and behaviors of other objects and then extending or specializing them.

The object being inherited is the base and the object doing the inheriting is the derived object.

Why the need for inheritance

Reusable code.

Basic Inheritance

Inheritance in C++ takes place between classes.
Example 1: Base class holds information about a person.

class Person
{
  public:
    std::string m_strName;
    int m_nAge;
    bool m_bIsMale;
 
    std::string GetName() { return m_strName; }
    int GetAage() { return m_nAage; }
    bool isMale() { return m_bIsMale; }
 
    Person(std::string strName="", int Age = 0, bool bIsMale=false)
      :
        m_strName(strName), 
        m_nAage(nAage), 
        m_bIsMale(bIsMale)
      { }
};

Example 2: A player is-a person.

// BaseballPlayer publicly inheriting Person
class BaseballPlayer : public Person
{
public:
    double m_dBattingAverage;
    int m_nHomeRuns;
 
    BaseballPlayer(double dBattingAverage = 0.0, int nHomeRuns = 0)
       : m_dBattingAverage(dBattingAverage), m_nHomeRuns(nHomeRuns)
    {
    }
};
 
#include <iostream>
int main()
{
    // Create a new BaseballPlayer object
    BaseballPlayer cJoe;
    // Assign it a name (we can do this directly because m_strName is public)
    cJoe.m_strName = "Joe";
    // Print out the name
    std::cout << cJoe.GetName() << std::endl;
 
    return 0;
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.