stu nicholls dot com | menu - Professional dropdown #3

Class and Objects


  • A class is an abstract idea that can be represented with data structures and functions.
  • The class combines data and functions (which work on those data) into a single programming unit.
  • Functions associated with a class are called methods. This is an ‘Encapsulation’.
  • Data and procedures are tied together logically.
  • The parts that make up a class can be protected from the rest of the program to varying degrees.
  • The programmer has control over the protection of individual entries in the class definition.
  • An object is said to be an instance of a class.
  • A class definition consists of two parts: header and body. The class header specifies the class name and its base classes.
  • The class body defines the class members.
  • Two types of members are supported:
  • Data members have the syntax of variable definitions and specify the representation of class objects.
  • Member functions have the syntax of function prototypes and specify the class operations, also called the class interface.
  • Class members fall under one of three different access permission categories:
  • Public members are accessible by all class users.
  • Private members are only accessible by the class members.
  • Protected members are only accessible by the class members and the members of a derived class.
  • The data type defined by a class is used in exactly the same way as a built in type.
  • An example program


    Explanation for the above program

    1) This line contains the class header and names the class as Point. A class definition always begins with the keyword class, followed by the class name. An open brace marks the beginning of the class body.
    2) This line defines two data members, xVal and yVal, both of type int. The default access permission for a class member is private. Both xVaJ and yVal are therefore private.
    3) This keyword specifies that from this point onward the class members are public.
    4,5,6)These three are public member functions. Both have two integer parameters and a void return type.
    7)This brace marks the end of the class body


  • The actual definition of the member functions is usually not part of the class and appears separately. Following code shows the separate definition of SetPt and OffsetPt.

  • Example
    Footer1