Home C++ Introduction Decisions Loops Input/Output Functions Stack and Heap References Arrays Searching and Sorting Recursion Pointers Character and Strings Structures Classes Inheritance Exceptions Templatess STL Modern C++ Misc Books ----

Classes


Contents

Encapsulation

We normally want to assign the properties with a private access and give functions public assess.
File: c5.cpp
#include <string>
#include <iostream>
using namespace std ;

class Person
{
   private:
    string firstName  ;
    string lastName ;
    int age ;
   public:
     void setFirstName(  string firstNameP )
     {
         firstName = firstNameP ;
     }
     string getFirstName()
     {
         return firstName ;
     }
     void setLastName(  string lastNameP )
     {
         lastName = lastNameP ;
     }
     string getLastName()
     {
         return lastName ;
     }
     void setAge(  int ageP )
     {
         age = ageP ;
     }
     int getAge()
     {
         return age ;
     }
     void print()
     {
         cout << "Name:" << firstName << " " << lastName
         << " Age: " << age << endl ;
     }
};

int main()
{
    Person personObj ;
    personObj.setFirstName ( "Robert" ) ;
    personObj.setLastName( "Newman" ) ;
    personObj.setAge( 82 ) ;
    personObj.print() ;
    return 0 ;
}
This approach has couple of advantages. The first being that
we can implement validation in one place. If we set the age as:

personObj.age = 82  ;

then a potential user of the class could inadvertently type:

personObj.age = 882

By restricting access to a function we can place the
validation in the function "setAge" :

       void setAge(  int ageP )
        {
             if ( age < 0 || age > 200 )
               {
                  cout << "Invalid age" << endl ;
                  return ;
               }

             age = ageP ;
         }

The other advantage is that we can change the data
properties inside our class without affecting how
the class got used. Lets say we changed

   int age ;

to

  unsigned char age ;

We can do so without the user changing the code that used the function. User called the function "setAge()" and that part does not change. This is possible because we have kept the implementation ( data part ) separate from the interface ( the public methods ) . This is called encapsulation .
Exercise:
1) Create a class "vehicle" that contains the properties "weight" , "top speed" and "number of wheels" and a method to print the properties. Create another class method to set and obtain the weight. Create an object of this class in the main function and set the weight and then use the print method to print the contents out.