Search code examples
c++classinheritanceoverridingprivate

Calling original inherited function after overriding it


I am trying to modify a private member of a class which was inherited from the base class. The problem is that in the derived class, I am overriding the method that sets the private member. In the code below, I want to modify both _a._time and b._time, using the overridden method setTime.

Base class

class timeClass
{
    public:
        void setTime(double time){ _time = time;}
        double getTime(){ return _time;}
    private:
        double _time;
}

Inhereted class 1

class a : public timeClass
{
    public:
        void doStuff(){ }
    private:
        double things;
}

Inhereted class 2

class bClass : public timeClass
{
    public:
        void setTime(double time)
        {
           _time = time; //can't access _time since its private
           _a.setTime = time;
        }
    private:
        aClass _a;
}

Is what I'm trying to do even possible? Thanks.


Solution

  • This is how yo should do it:

    void setTime(double time)
    {
       timeClass::set_time(_time);
    // ^^^^^^^^^^^
    // Will invoke the base class's set_time() function
    
       _a.setTime(time);
    //    ^^^^^^^^^^^^^
    //    Will invoke setTime() on the `_a` subobject
    }