How can I hide a class in C++?

后端 未结 4 617
旧时难觅i
旧时难觅i 2021-01-11 23:49

Let\'s say I have 2 classes that I want to be visible (within a given header file) and one class that is their ancestor, which one I want to be visible only to the previousl

4条回答
  •  深忆病人
    2021-01-12 00:26

    It is not possible.

    C++ requires that a class be fully defined at the point it is used as a base, and because of its include mechanism anything that is fully defined at the point of definition of a class is necessarily visible to all who can see the definition of said class.

    C++ has mechanisms to protect against Murphy (accidents) but not against Machiavelli (hacks).


    That being said, the purpose is itself dubious, the only reason I can fathom would be to prevent the user from relying on the fact that your Derived class derives from this Fantom base. Well, deriving privately: class Derived: private Fantom {}; or using composition instead class Derived { private: Fantom _fantom; }; would both achieve this.

提交回复
热议问题