Search code examples
c++classmultiple-inheritance

How to interpret a nested inheritance class structure?


I am modifying some C++ code that start with the following code:

class AAAA {
public:
    class BBBB : public CCCC {   // CCCC from include CCCC.h
        friend class AAAA;
        typedef ... ;

    public:
        BBBB() {}
        BBBB(AAAA& thething, uint8_t a = 1) {
           init(&thething, a);
        }
        virtual ~BBBB(){}
//...
}

However as non-professional C++ programmer, this is very confusing and daunting.

Why would a subclass have its super class as a friend class?

What is the meaning of:

(a) class BBBB : public CCCC, and
(b) BBBB() {} followed by
(c) virtual ~BBBB(){}, in this case?


I have already looked at the following SO answers:


Solution

  • First, I would look at BBBB and CCCC by themselves.

    class BBBB : public CCCC {   // CCCC from include CCCC.h
        friend class AAAA;
        typedef ... ;
    
    public:
        BBBB() {}
        BBBB(AAAA& thething, uint8_t a = 1) {
           init(&thething, a);
        }
        virtual ~BBBB(){}
    }
    

    BBBB is a pretty standard class that derives from CCCC. The only unusual thing is the friend class AAAA, which allows the methods in AAAA to access private (and protected) methods and fields in BBBB.

    The fact that BBBB is nested in AAAA means that to use BBBB, you'd have to access it with AAAA::BBBB b;, and that BBBB can access private (and protected) methods and fields in AAAA.

    Why would a subclass have its super class as a friend class?
    What is the meaning of:
    (a) class BBBB : public CCCC, and
    (b) BBBB() {} followed by
    (c) virtual ~BBBB(){}, in this case?

    AAAA is not the super class of BBBB, it is the enclosing class. See above.

    (a) indicates that BBBB inherits from CCCC. (b) is the default constructor. (c) is the destructor, and for classes using inheritance it is recommended to make destructors virtual.