Search code examples
c++member-variables

Accessing Member Variable Inside Overridden Base Class Function


How do I access member variables inside an overridden base class function?

//Overridden base class function
void handleNotification(s3eKey key){
     //Member variable of this class
     keyPressed = true; //Compiler thinks this is undeclared.
}

Complier is complaining that keyPressed is not declared. The only way I can figure out how to access it is declare keyPressed as a public static variable and then use something like:

ThisClass::keyPressed = true;

What am I doing wrong?

//Added details-----------------------------------------------------------

ThisClass.h:

include "BaseClass.h"

class ThisClass: public BaseClass {
private:
    bool keyPressed;
};

ThisClass.cpp:

include "ThisClass.h"

//Overridden BaseClass function
void handleNotification(s3eKey key){
     //Member variable of ThisClass
     keyPressed = true; //Compiler thinks this is undeclared.
}

BaseClass.h:

class BaseClass{
public:
    virtual void handleNotification(s3eKey key);
};

BaseClass.cpp

include 'BaseClass.h"

void BaseClass::handleNotification(s3eKey key) {
}

Solution

  • The correct way to override a function is as follows.

    class base {
    protected:
      int some_data;
      virtual void some_func(int);
    public:
      void func(int x) { some_func(x); }
    };
    
    void base::some_func(int x)
    { /* definition, may be in some source file. */ }
    
    class derived : public base
    {
    protected:
      virtual void some_func(int);  // this is not base::some_func() !
    };
    
    void derived::some_func(int x)
    {
      some_data = x; // example implementation, may be in some source file
    }
    

    edit Note that base::some_func() and derived::some_func() are two different functions, with the latter overriding the former.