Adding Changing And Hiding Members In A Derived Class

Introduction

To add new functionality to a derived class, simply declare that functionality in the derived class like normal.

Redefining functionality

When a member function is called with a derived class object, the the compiler first looks to see if that member exists in the derived class. If not, it begins walking up the inheritance chain and checking whether the member has been defined in any of the inherited classes. It uses the first one it finds.

To modify a function the way a function defined in a base class works in the derived class, simply redefine the function in the derived class.

Example 1

#include <iostream>
using namespace std;
 
class Base
{
protected:
    int m_nValue;
 
public:
    Base(int nValue)
        : m_nValue(nValue)
    {
    }
 
    void Identify() { cout << "I am a Base" << endl; }
};
 
class Derived: public Base
{
public:
    Derived(int nValue)
        :Base(nValue)
    {
    }
 
    int GetValue() { return m_nValue; }
 
    // Here's our modified function
    void Identify() { cout << "I am a Derived" << endl; }
};
 
int main()
{
    Base cBase(5);
    cBase.Identify();
 
    Derived cDerived(7);
    cDerived.Identify()
 
    return 0;
}

Adding to existing functionality

Sometimes we don’t want to completely replace a base class function, but instead want to add additional functionality to it.

class Derived: public Base
{
public:
    Derived(int nValue)
        :Base(nValue)
    {
    }
 
    int GetValue() { return m_nValue; }
 
    void Identify()
    {
        Base::Identify(); // call Base::Identify() first
        cout << "I am a Derived"; // then identify ourselves
    }
};

Hiding functionality

Example: You can change a base member's access specifier by naming the member to have it's access changed in the derived class under the new access specifier.

class Base
{
private:
    int m_nValue;
 
public:
    Base(int nValue)
        : m_nValue(nValue)
    {
    }
 
protected:
    void PrintValue() { cout << m_nValue; }
};
 
class Derived: public Base
{
public:
  Derived(int nValue) :
      Base(nValue)
         {}
 
// Base::PrintValue was inherited as protected so the public has no access.
// But we're changing it to public by declaring it in the public section.
  Base::PrintValue;
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.