Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, is it possible to have a class inherit from one of its member classes?

The following code doesn't compile because the compiler doesn't know what foo::bar is when it encounters it.

class foo : foo::bar {
    class bar {
    }
}

Is there any way to make this code (or some variation of it) compile?

like image 462
Shum Avatar asked Jan 16 '26 21:01

Shum


1 Answers

If the inheritance from bar is an implementation detail and the goal is to avoid polluting the global namespace (or the library's namespace), a common approach is to put these implementation details in a namespace named detail. This is a convention used in libraries like Boost, for example.

namespace super_cool_library {

    namespace detail {
        class bar { };
    }

    class foo : detail::bar {
    };

}

The detail namespace is, admittedly, just a convention, but most people understand that within said namespace there be dragons.

Edits:

As Emilio Garavaglia suggests, foo would need to befriend detail::bar if detail::bar should need to have the same access to foo that a C++11 inner class would have.

like image 113
chwarr Avatar answered Jan 19 '26 09:01

chwarr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!