How to Create a Class in C++

To get most out of any programming language, you have to write efficient and simple codes. In terms of efficiency, classes are the best way to make efficient programs. Class is a type of data structure that can have multiple data types inside and also multiple functions. Writing and using classes in C++ is a simple but tricky task. First of all we have to write the classes and then to use them we have to declare their instances called objects and they have the same properties as of the respective class. There are many other types of classes apart from simple classes including sub classes etc., but here only declaration and usage of a simple C++ class will be discussed. Following step by step guide will help you to create classes in C++ using simple steps.

Instructions

  • 1

    Class is declared using “class” keyword. So whenever you declare a class an optional list of object names and access specifiers get associated with it.

  • 2

    While writing the body of a class, you have to write the access specifiers, class’s member functions or data variables.

  • 3

    While assigning access specifiers, keep in mind that you have three options to do so. If access specifier is private, it can only be accessed by the members of the class and the associates of the members. If the specifier is protected, it can only be accessed by the members of the respective class and if it is public, all of the members are accessible publicly.

  • 4

    Example:

    Following example will help you to write your first class in C++. It simply declares some access specifiers and member functions. An object of that class is also declared.

    Class shape{

    private  int   width, height;

    public void draw(int, int){

    //statements of your choice to draw a shape

    }

    }rect;

    In above code, a class with name shape is created and then an instance (object) of that class is declared named rect.

Leave a Reply

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


nine − 8 =