2

I am trying to manipulate 'registerTable' with 'ChargerClass::SystemStruct::initNested()', with a function from an object passed in during initialisation 'interface'.

The reason I want to nest is to enable the use of dot notation to use the Class members; there will be a lot of functions in this class and dot notation will make clear what part of the class is being utilised.

'chargerHAL_r hal' must be passed in as it is an abstraction layer object to allow for multiple communication protocols to be used with the ChargerClass.

If initNested() is within 'SystemStruct', I get compiler errors:

  • invalid use of non-static data member 'ChargerClass::interface'
  • invalid use of non-static data member 'ChargerClass::registerTable'

However, if initNOTNested() is in the parent class ChargerClass and not nested in SystemStruct. it compiles just fine.

I have included comments in the code snippet for both initNested() and initNOTNested();

I am using C++11, and since this version, nested-class access to enclosing-class members is valid, no?

What am I missing?

struct chargerHAL_r {
    static void readAllRegisters(uint8_t *regTable);
};


class ChargerClass {
public:
    ChargerClass(chargerConfig_r config, chargerHAL_r hal) {
        interface = hal;
    }


    struct system_r {
        bool initNested(); /* Compiler throws error */
    };

    bool initNotNested(); /* Compiles OK */


private:
    uint8_t registerTable[20];
    chargerHAL_r interface;
};


/* Compiler throws error */
bool ChargerClass::system_r::initNested() {
    interface.readAllRegisters(registerTable);
}

/* Compiles OK */
bool ChargerClass::initNotNested() {
    interface.readAllRegisters(registerTable);
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Mike
  • 43
  • 5

1 Answers1

1

You may have misunderstood what a nested class is.
A nested class is an independent class with special access privileges. That means defining an instance of system_r will not be related anyway to ChargerClass, hence it won't know what interface or registerTable you're talking about.
I would consider this as a workaround for your problem.

Narek Bojikian
  • 259
  • 3
  • 13
  • Ok. So, is it better practice to ditch the aim of implementing dot notation for readability and adding complexity of using references (as per the workaround)? Versus having many functions on one-level with verbose names and not needing to use references? – Mike Apr 26 '18 at 07:47
  • I'd rather go for the "workaround", I would even go for making an abstract independent class for 'system_r' and a concrete derived class of it so that it'd be easier to test and extend your class https://en.wikipedia.org/wiki/Dependency_injection – Narek Bojikian Apr 27 '18 at 07:33