I have a class that only really ever needed by classes in a certain class hierarchy. I wanted to know if it is possible to nest the class in the highest class's protected section and have all the other classes automatically inherit it?
+6
A:
"Inherit" is the wrong word to use since it has a very specific definition in C++ which you don't mean, but yes you can do that. This is legal:
class A {
protected:
class Nested { };
};
class B : public A {
private:
Nested n;
};
And code that is not in A or something that derives from A cannot access or instantiate A::Nested.
Tyler McHenry
2008-11-21 01:30:00
Hmm What happens if class B provides an accessor method for Nested n? Probably a compile error?
Kieveli
2008-11-21 02:37:23
MSalters
2008-11-21 13:08:52
Hm, you're correct. A::Nested is accessible since B can return an A::Nested from a public function. B it's still not instantiable, so interestingly this leads to the situation where the caller is not allowed to store the return value of B::Get_n().
Tyler McHenry
2008-11-21 14:20:57