Search code examples
c++inheritancesubclasspure-virtual

C++ Calling a superclass function of the same virtual function


I'm relatively new to c++ so I'm getting used to the scope of functions and variables in this environment. One issue I can't solve is being able to call a function defined in a subclass of a class which declares this function as pure virtual. Here's my class structure:

class Clock{

    public:
        virtual void Tick() = 0;
        std::string Print();

        //Mutators
        int Seconds();
        int Minutes();
        int Hours();
        void setTime(int secs, int mins, int hours);

        //Accessors
        int getSecs(){ return _secs; }
        int getMins(){ return _mins; }
        int getHrs(){ return _hours; }
    private:
        int _secs, _mins, _hours, _days = 0;
    };

    class NormalClock : public Clock{

    public:
        void Clock::Tick();
    private:
    };

    class AlarmClock : public Clock{

    public:
        void Clock::Tick();
        bool CheckAlarm();
        void SetAlarmTime(int hrs, int mins, int secs);
        int GetAHrs();
        int GetAMins();
        int GetASecs();
    private:
        int _alarmhrs, _alarmmins, _alarmsecs;
    };

In my source file I want to define a body for the Tick() function in the AlarmClock class. But within this function I want to call the Tick() function from it's superclass, the NormalClock class. My issue is that when I do so without defining any objects to work off of, I can't call the superclass Tick() function as my IDE (VS2013) thinks I'm referring to the Tick()from the current class (the AlarmClock subclass). I looked around on the web and determined that it would probably require the use of the using keyword, but I've been unsuccessful in implementing it properly. Here's the function I'm trying to build for reference:

void AlarmClock::Tick(){

    NormalClock::Clock::Tick();

    if (this->CheckAlarm()){ cout << "\nAlarm! @ " << this->Print() << "\n\n"; }
}

There's no errors in VS when calling the function as above, but the compiler complains of a static reference to a non-static member, which is understandable.


Solution

  • You were close, but your code has a few problems.

    1. AlarmClock does not inherit from NormalClock
    2. In AlarmClock::Tick call NormalClock::Tick() instead of NormalClock::Clock::Tick()
    3. In NormalClock change Clock::Tick to Tick in your class declaration.