Home > OOP > Classes in C++

In Programming classes are user-defined data types having their own data members (variables) and member functions (functions/methods). These data members and member functions can be accessed by creating instance(s) of class called objects. Classes are abstraction of objects declaring and defining characteristics and behavior of objects. Syntax for creating a c++ class is:

class Class_Name
	//data members and member functions

class is reserve word to create a class.
Class_Name is the name of the class which follows same rules as for a variable name.

There is another optional rule in naming a class is that its name must start with a capital letter.
Most importantly class/es definition must end with a semi colon (;) as shown above.
A few important things while defining a class are:

  • Usually data members are private or protected.
  • And Member functions are public.

You can define the member functions both inside and outside the class body. To define a function outside class body we must declare function inside class body.

C++ access specifiers

C++ provides three types of access specifiers.

Private: –

Block of code or statements written under this specifier are only accessible within the same class. So anything you write under private you can’t access it outside the class. By default, access specifier for any class is private.

Protected: –

Code or statements written under protected block can only be accessed with in the class as well as its derived classes. i.e. in both parent and child classes (Inheritance).

Public: –

Public specifier grants public access to the data members and member functions of the class. You can access them both inside and outside the class.

Below table shows access control

Same classesyesyesyes
Derived classesyesyesno
Outside classesyesnono


class object_Test_class
          int no1;
          float no2;
          void function_A()
               no1 = 10;
          float function_B()
               no2 = 23.5;
               return no2;

Above code will create a class named object_Test_class and we can create any number of objects for object_Test_class inside main function of the program.

C++ class representation:
c++ class data members and member functions

3 thoughts on “Classes in C++

  1. Pingback: Objects in C++
  2. Mainy aik program bnana Hai Gene k naam say aur us say classes bhi hn aur main us program main Gene ki attributes bhi daalna chahti hn aur phr un kay mutabiq different functions bhi hn + cccfiles must bhi included in header file
    But I don’t know how to do it

Leave a Reply

Your email address will not be published. Required fields are marked *