05 - C++ Classes

In this section of the tutorial, you will learn the following:

  • Declaring and Defining Classes
  • Implementing the concept of Data Abstraction
  • Implementing the concept of Data Encapsulation
  • Creating Objects

5.1 C++ Classes

A class in C++, is a user-defined type. It contains data and functionality. The class definition does not occupy any space in the memory. Let us declare a class date in C++ as follows:

Class date 
{        
    int dd;
    int mm;
    int yy;
    void valid(int d, int m)
    {
        if ( d<31)
            cout<<”Invalid date”;
        if (m>12)
            cout<<”Invalid month”;
    }    
};

The class date has three variables (data) and a member function valid. This function is known as the member function of the date class.

5.1.1    C++ Data Abstraction

The object of creating a class in C++ is to bundle data and its functionality. Classes in C++ implement the concept of data abstraction.

5.1.2    C++ Encapsulation

In C++, you can implement the concept of encapsulation by using access specifiers. An access specifier controls the visibility of the members of a class. There are three types of access specifiers; private, public and protected.

  • Private: If the members of class are declared as private, then they are accessible only within that class. By default, in C++, members of a class are private. A common practice is to declare the variables in a class as private and the functions as public.
  • Public: Public members are accessible from within the class and outside the class.
  • Protected: For more information, see Protected Access Specifier.

5.1.3    Encapsulation Example

Class date 
{
        private:
            int dd;     
            int mm;
            int yy;
        public:
            void valid(int d, int m)
            {
                if ( d<31)
                    cout<<”Invalid date”;
                if (m>12)
                    cout<<”Invalid month”;    
            }    
};

 

 

 

Like us on Facebook