0

I have a public header that has class X. X has a private member of nested type U::V. As I understand, normally, you just forward declare the types but I cant forward declare nested type. U::V is in a private header so I cannot #include them from a public header. What do I do to have X know of class U::V? Summary of my code:

// in include/mylib/box.h
class X {
 public:
  X();
  //...
 private:
  U::V stuffs; // how do I have this declaration work?
};

// in some private file
class U {
  class V{
  // ..
  };
};
  • What distinction are you making between “public” and “private” headers? Why do you feel you can’t include one from the other? – Sneftel Jan 31 '21 at 18:53
  • 1
    Incidentally, you can’t have a member variable of a forward-declared type, regardless of whether it’s a nested type. – Sneftel Jan 31 '21 at 18:55
  • You might be looking for [pimpl idiom](https://en.cppreference.com/w/cpp/language/pimpl). See also [this question](https://stackoverflow.com/questions/8972588/is-the-pimpl-idiom-really-used-in-practice) – Igor Tandetnik Jan 31 '21 at 18:55
  • I had one suggestion that the pimpl idiom might help, I can just put U::V in a pimpl class. I feel like it's applying a whole idiom for a small problem. Is there a simpler or better solution? – hackinghorn Jan 31 '21 at 19:03
  • ahh, thanks, guys, – hackinghorn Jan 31 '21 at 19:05
  • A nested type is a member of the enclosing class. In general you cannot declare class members without having the class defined. – n. 'pronouns' m. Jan 31 '21 at 19:25

3 Answers3

1

What do I do to have X know of class U::V?

Only way to have a member of type U::V in X is to define the type U::V before defining X.

You can avoid storing the member directly by using the PIMPL idiom. In short, you would store a pointer to a forward-declared type.

eerorika
  • 181,943
  • 10
  • 144
  • 256
0

This question was answered by Adam Rosenfield here.

You'll have to un-nest at least one of the nested classes

Nadim Z
  • 11
  • 3
0

I just realized this happens because I got an incomplete class definition, not because it's a nested class. Thanks, everyone.