user180247
user180247

Reputation:

Can a member class inherit from it's parent?

While considering "creative" (ie bizarre) solutions to an odd problem, one particular idea triggered my curiosity. It's not an idea I'm likely to use, but I'd still like to know if it's legal according to the standard.

A simple example would be...

class base_t
{
  private:
    //  stuff

  public:
    //  more stuff

    class derived_t : public base_t  //  <--- weirdness here
    {
      //  ...
    };      
};

Part of the weirdness - since derived_t inherits from base_t which contains derived_t, it seems like derived_t contains itself.

So - is this a valid-but-strange-and-scary thing of a similar kind to the curiously recurring template pattern, or is it illegal?

EDIT - I should perhaps mention that the reason I thought of this was trying to avoid some namespace pollution. Having a class as a member avoids introducing another global class, but that second class needs to share a lot from the first.

If it was just one pair of classes it wouldn't be an issue, but this is for a code generator.

Upvotes: 9

Views: 176

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283624

It's legal, but maybe not the way you arranged your code. A base class has to be complete at the point when it's used, but isn't until the closing brace of the definition. So try forward-declaring the nested class:

class base_t
{
  private:
    //  stuff

  public:
    //  more stuff

    class derived_t;
};

class base_t::derived_t : public base_t
{
  //  ...
};      

Upvotes: 9

Related Questions