How to Create a C++ Class

A class is a data structure that contains related data and functions and is a unit of object-oriented programming. Objects are an instantiation of a class and share the same properties although their contents may differ. Classes may inherit properties from other classes and support the encapsulation of data structures through access specifiers. The following steps explain how to create a C++ class.

Instructions

    • 1

      Define the class using the class keyword. This will provide the class a name, an optional list of access specifiers and an optional list of object names.

    • 2

      Declare members as either access specifiers, data or functions within the body of the class statement.

    • 3

      Provide the access specifiers to indicate one of the 3 levels of access in C++. Private members are only accessible by members of that class and their associates. Members who are protected are accessible by members in that class, any derived classes and any associates of those classes. When the object is visible public members are accessible. The default is private.

    • 4

      Learn the syntax of the class statement:

      class class_name
      {
      access_specifier_1:member1;
      access_specifier_2:member2;
      ...
      access_specifier_n:membern;
      } object_names;

    • 5

      Look at the following example of the class statement:

      class CTest {
      int i, j;
      public:
      void set_values (int,int);
      int total (void);
      } test;

      Note that the integers i and j do not have an access specifier and are therefore private. The function set_values and the integer total are public.

Related Searches:

Resources

Comments

You May Also Like

Related Ads

Featured