Introduction to Classes



Introduction to Classes
Introduction to Classes

Basic Concept

In C++, the class is the construct primarily used to create objects.

Explanation
A class is a programmer-defined data type that describes what an object of the class will look like when it is created. It consists of a set of variables and a set of functions. Here is the general format of a class declaration.

Syntax
class ClassName             // Class declaration begins with
{                 // the key word class and a name.
                 Declarations for class member variables
           and member functions go here.

};                 // Notice the required semicolon.

We will learn how to implement a class by building one step by step. Our example will be the simple Circle class The first step is to determine what member variables and member functions the class should have. In this case we have determined, as already described, that the class needs a member variable to hold the circle’s radius and two member functions: setRadius and getArea.

Once the class has been designed, the next step is to write the class declaration. This tells the compiler what the class includes. Here is the declaration for our Circle class. Notice that the class name begins with a capital letter. Although this is not strictly required, it is conventional to always begin class names with an uppercase letter.

Program
class Circle
{         private:
                  double radius;
        public:
                           void setRadius(double r)
{      
               radius = r; 
}
        double getArea()
{           
                                 return 3.14 * pow(radius, 2);
 }
};


Previous
Next Post »