How to Hide Object Implementation in C++

In the world of C++, library producers and client programmers use the libraries to put together applications that are often bigger libraries. Libraries consist of classes. A C++ class has access control features that define strict boundaries between the class producer and the client programmers. These are necessary to keep client programmers from touching critical sections of code and to enable library producers to make internal changes without notification.

Things You'll Need

  • Book on C++ programming
Show More

Instructions

    • 1

      Understand the access specifiers provided by C++ that determine the class boundaries. These are indicated by the explicit keywords "public," "private" and "protected." By identifying a member function with one of these keywords, you control the access level of that member function.

    • 2

      Use the "public" keyword to render a definition available to anyone, including client programmers.

    • 3

      Apply the "private" keyword when you don't want anyone besides yourself to access a class definition. Private definitions can only be accessed by other member functions that belong to the class in question. Think of "private" as a firewall that protects the internal implementation of a definition from a client programmer.

    • 4

      Declare a definition "protected" when you want only inheriting classes to access that definition. Inheriting classes or classes that derive functionality from a class can't access private definitions, but they can access definitions marked as protected.

    • 5

      Refer to the following example to gain a better understanding of Steps 2 to 4 and access control:


      class CFile {

      public:

      int Open(const char* fileName);

      private:

      bool FileExists() const;

      protected:

      int PixelCount();

      };


      // private function "FileExists" can be used by member functions in definition

      int CFile::Open(const char* filename) {

      if (true == CFile::FileExists())

      throw ...

      }


      // inheriting class can use protected function "PixelCount" of base class

      class CImageFile: public CFile {

      public:

      void SomeFunc() {

      int x = CFile::PixelCount();

      };

      };


      // execution area

      int main() {

      CFile file;

      file.Open(referral.txt);

      if(true == file.Exists()) // compiler error

      int x = file.PixelCount; // compiler error

      }

Tips & Warnings

  • The terms "definition" and "member function" are used interchangeably in this article.

  • The code demonstrated in Step 5 won't compile. It's only for illustration purposes.

Related Searches:

Resources

Comments

You May Also Like

Related Ads

Featured