-3

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) {
}
user3564870
  • 385
  • 2
  • 13

2 Answers2

2

Is this method defined outside of the class definition? In other words, is your code structured like so:

class ThisClass {
    ...
};

// method defined outside of the scope of ThisClass declaration, potentially
// in a completely different file
void handleNotification(s3eKey key) {
    ....
}

If so, you need to declare the method like this:

void ThisClass::handleNotification(s3eKey key){
    keyPresssed = true;
}

Otherwise the compiler will not know that the handleNotification() method being implemented is the one which belongs to ThisClass. Rather, it will assume that it is not part of the ThisClass implementation, so it won't have automatic access to ThisClass's variables.

Alex Kleiman
  • 709
  • 5
  • 14
1

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.

Walter
  • 44,150
  • 20
  • 113
  • 196
  • Thanks! So you have to re-declare something that was already declared in the base class? – user3564870 Aug 26 '14 at 17:25
  • 1
    @user3564870, that is correct. That's the only way to tell the compiler that the derived class has an implementation that overrides the implementation in the base class. – R Sahu Aug 26 '14 at 17:32