Cant access to base class field from derived in virtual method overriding


class IResetable
{
    public: virtual void Reset(void) = 0;
};

template<typename ConfigStruct>
class Config
{

// Fields
public:
    const ConfigStruct defaults;
    ConfigStruct config;
    
// Methods
protected:
    Config(ConfigStruct defaults)
    : defaults(defaults)
    {

    }

// Methods
public:
    virtual bool SetConfig(ConfigStruct new_config)
    {
        config = new_config;
        return true;
    };

    virtual ConfigStruct GetConfig(void)
    {
        return config;
    };

    virtual bool RestoreDefaultConfig(void)
    {
        config = defaults;
        return true;
    }

    virtual ConfigStruct GetDefaults(void)
    {
        return defaults;
    };
};


template <typename ConfigStruct, typename StateStruct>
 class AppliedEntity 
: public IResetable
, public Config<ConfigStruct>
{
    StateStruct state;

public:
    AppliedEntity(const ConfigStruct defaults)
    : Config<ConfigStruct>(defaults)
    {
    }

    virtual void Init(void)
    {
        config.open_delay = 1;
    }

    virtual bool SetConfig(ConfigStruct new_config)
    {
        Reset();
        config = new_config;
        Reset();
        return true;
    }
};


struct FlapConfig
{
    int open_delay;
    int port;
};

struct FlapState
{
    int elapsed_time;
};

class Flap 
: public AppliedEntity<FlapConfig, FlapState>
{
private: 

public:

    Flap(FlapConfig config) 
    : AppliedEntity<FlapConfig, FlapState>(config)
    {

    }

    void Reset(void)
    {

    }
     
};

FlapConfig config = { 1, 1 };
Flap flap(config);


int main(void)
{
    flap.config.open_delay = 0;
}

Error:

Output of x86-64 gcc 11.2 (Compiler #1)
<source>: In member function 'virtual void AppliedEntity<ConfigStruct, StateStruct>::Init()':
<source>:65:17: error: 'config' was not declared in this scope; did you mean 'Config'?
   65 |                 config.open_delay = 1;
      |                 ^~~~~~
      |                 Config
<source>: In member function 'virtual bool AppliedEntity<ConfigStruct, StateStruct>::SetConfig(ConfigStruct)':
<source>:71:17: error: 'config' was not declared in this scope; did you mean 'Config'?
   71 |                 config = new_config;
      |                 ^~~~~~
      |                 Config
Compiler returned: 1

https://godbolt.org/z/6hfddnGbs

>Solution :

To solve this you have to replace config.open_delay = 1; by:

this->config.open_delay = 1;

and then also replace config = new_config; by:

this->config = new_config;

The program then works(no compiler error) as can be seen here.

Note the this-> i have added in both the corrected statements.

Here’s the rule:

the compiler does not look in dependent base classes when looking up nondependent names .

Here’s a good article for reading more about this.

Leave a Reply