C++ Class

Class is defined as a collection of similar objects. Class is the backbone of object oriented programming language.

Class is a use defined data type which contains variables known as data members and functions known as member functions of the class.

Access Level of Class



There are three Access levels of Class:
  • Private
  • Protected
  • Public


Private



  • This is default access level of the members of a class.
  • If we don't define access level for member o a class then it is considered as private.
  • Members of the class declared as PRIVATE are hidden from outside world.
  • The private members of class can be used by member functions and friends of class in which they are declared.


Protected



  • This access level is similar to private.
  • Members of class declared PROTECTED can be used by member functions, friend functions of the class as well as member functions of the child class.
  • Protected members of a class can't be accessed directly through the object of class but they can be accessed through member function of the same class or child class.


Public



  • This is the less restricted type of Program Access Level.
  • Member of class declared PUBLIC are available to the outside world.
  • Member of class can be used by member functions, friends of class as well as any other function outside the class.

Syntax


class class_name
{
   private:
        [data members]
        [member functions]
   protected:
        [data members]
        [member functions]
   public:
        [data members]
        [member functions]
}

Program to demonstrate Class.



#include<iostream.h>
#include<conio.h>
class data
{
    private:
        int a; 
        float b;
    public:
        void read()
        {
             a=10;
             b=12.5;
         }
         void show()
         {
             cout<<"\na = "<<a;
             cout<<"\nb = "<<b;
         }
};
void main()
{
    clrscr();
     data d;
     d.read();
     d.show(); 
    getch();
}


Output


a = 10
b = 12.5

Scope Resolution Operator ( :: )



Scope resolution operator is used to specify the link between class and member functions which we want to define outside the class. This operator also creates a distinction between normal functions and member functions of the class.

Program to show use of Scope Resolution Operator (::)




#include<iostream.h>
#include<conio.h>
class data
{
    private:
        int a; 
        float b;
    public:
        void read();
        void show();
};
void data::read()
 {
      a=10;
      b=12.5;
 }
 void data::show()
 {
      cout<<"\na = "<<a;
      cout<<"\nb = "<<b;
 }
void main()
{
    clrscr();
     data d;
     d.read();
     d.show(); 
    getch();
}


Output


a = 10
b = 12.5

Back To Top