C++ Protection Types

 

There are 3 levels of protection for class members in C++:

  • public

    Any class, function can access variables or functions or classes of this type.

  • private

    Only the class itself can access variables of functions of this type.


  • protected

    protected members are only accessible to the class and also to subclasses,

You put members in sections by their protection level.

You can have as many sections of each protection level in a class declarations as you would like.

If no modifier is specified, the protection level defaults to private.

C++ also has an additional form of control over protection levels called friendship that allows for a finer grain of protection. You will probably not need to use this in the majority of your coding career

Recall a previous example

Define the class in file date.h (specification file)
    

class Date {

    int day, //internal storage scheme
                  month, //this is private to the class
         
year;

         char *message; //string message reflecting date

   public:
     void new_date(int,int,int); //method to change the date

          char* give_date(); //report date
};

Now define the methods in file date.cpp (implementation file)

#include "date.h"

void date::new_date(int d, int m, int y)
{
   day = d;
   month=m;
   year=y;
}

void date::give_date()
{
   char *buf= new char[80];

   sprintf(buf, "%s %d, %d", mname[month],day,year);


   return buf;
}

 

//constructor

date::date(....)
{ //...code here }


//destructor
date::~date()
{ //...code here }

 

 

© Lynne Grewe