Q&A: Inheritance

What do the different accessibility settings mean?

They regard where member variables of a class are accessible:

Accessibility Class' functions Child class' functions External functions
Public Class functions can use public member variables Child class functions can use public member variables External functions can use public member variables
Protected Class functions can use protected member variables Child class functions can use protected member variables External functions CANNOT use protected member variables
Private Class functions can use private member variables Child class functions CANNOT use private member variables External functions CANNOT use private member variables

What is inheritance?

A child class inheriting from a parent class will "inherit" all its parents PUBLIC and PROTECTED member functions and variables. That way, you can keep using those functions, but don't have to define them a second time, thus cutting down on duplicate code.

When a child inherits from a parent, which member variables and functions are inherited?

PUBLIC and PROTECTED members.

Write some example code of how to use inheritance in a class' declaration.

class Person
{
  public:
  void Display();
  void SetName( string name );
  string GetName() const;

  protected:
  string m_name;
};

class Student : public Person // Inherits from Person
{
  public:
  void Display(); // We can RE-DEFINE this function if we want!

  // void SetName( string name ); // These already exist, don't need to re-define!
  // string GetName();

  void SetGpa( float gpa );
  float GetGpa() const;

  private:
  float m_gpa;
};

What is composition?

When a class CONTAINS another class within it, as a member variable.

class Building
{
  private:
  // These Room objects are contained within Building
  Room living_room;
  Room bathroom;
  Room kitchen;
};

How do you override a parents' version of a function from the child class? How can you call the parents' version of a function from a child class' function?

Re-declare and re-define the function, and you can call the parents' version by prefixing PARENTNAME:: to the function's name as a call.

void Student::Display()
{
  Person::Display(); // Call parent version

  // Now display stuff related to student
  cout << "GPA: " << GetGpa() << endl;
}

Author: Rachel Wil Sha Singh

Created: 2023-10-31 Tue 10:07

Validate