Making classes public to other classes in C++

浪子不回头ぞ 提交于 2019-11-30 07:08:46

There's a substantial difference between making the class public and making its contents public.

If you define your class in an include file (.h file) then you are making your class public. Every other source file that includes this include file will know about this class, and can e.g. have a pointer to it.

The only way to make a class private, it to put its definition in a source (.cpp) file.

Even when you make a class public, you don't necessarily have to make the contents of your class public. The following example is an extreme one:

class MyClass
   {
   private:
      MyClass();
      ~MyClass();
      void setValue(int i);
      int getValue() const;
   };

If this definition is put in an include file, every other source can refer to (have a pointer to) this class, but since all the methods in the class are private, no other source may construct it, destruct it, set its value or get its value.

You make the contents of a class public by putting methods from it in the 'public' part of the class definition, like this:

class MyClass
   {
   public:
      MyClass();
      ~MyClass();
      int getValue() const;
   private:
      void setValue(int i);
   };

Now everybody may construct and destruct instances of this class, and may even get the value. Setting the value however, is not public, so nobody is able to set the value (except the class itself).

If you want to make the class public to only some other class of your application, but not to the complete application, you should declare that other class a friend, e.g.:

class SomeOtherClass;
class MyClass
   {
   friend SomeOtherClass;
   public:
      MyClass();
      ~MyClass();
      int getValue() const;
   private:
      void setValue(int i);
   };

Now, SomeOtherClass may access all the private methods from MyClass, so it may call setValue to set the value of MyClass. All the other classes are still limited to the public methods.

Unfortunately, there is no way in C++ to make only a part of your class public to a limited set of other classes. So, if you make another class a friend, it is able to access all private methods. Therefore, limit the number of friends.

You can use friendship.

class A { friend class B; private: int x; };
class B { B() { A a; a.x = 0; // legal };

If B has a strong interdependence to A, i suggest you use a nested class. Fortunately, nested class can be protected or private.

class A {
protected:
     // the class A::B is visible from A and its
     // inherited classes, but not to others, just
     // like a protected member.
     class B {
     public:
         int yay_another_public_member();
     };
public:
     int yay_a_public_member();
};
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!