Classes and Objects

Introduction

A class is a fundamental building block of the object oriented programming language C++. Bjarne Stroustup, the originator of C++ language, gave the name "C with classes" to this language initially. The class is the most important feature of C++. It implements OOP concepts and ties them together.

A class is a way to bind data (describing an entity) and its associated functions together. In C++, a class makes a data type that is used to create objects of this same type.

The prerequisites for classes and objects are structures and the functions. A structure provides a way to group data elements and a function organizes program actions into a named entity.

Class Specification

A class specification consists of two parts:

1. Class declaration

2. Class method definition

Declaration of a Class

A class is declared using the class keyword. the syntax of a class declaration is similar to that of a structure.

The general form of a class declaration is :

class class_name

{

permission_label_1;

member1;

permission_labe_2;

member2;

.....

} object_name;

where,

1. Class_name is a tag-name for the class (user-defined types). While the class-name is technically optional, from the practical point of view it is virtually always needed. the reason for this is that the class-name becomes a new type name that is used to declare objects of the class.

2. Object-name (which is also optional) consisting of one or several valid object identifiers.

3. Members that can be either data or function declarations contained in the body of the declaration.

i. Data Members are the data tpe properties that describe the characteristics of a class. Data members are optional in a class declaration.

ii. Member functions are the set of operations that may be applied to objects of that class. Memeber functions are also optional in a class

declaration. They are referred to as the class-interface.

4. Optional permission (aceaa) labels, that can be any of these three keywords: private, public, or protected. These access levels control the access given to the members from within the program.

i. Private members of a class are accessible only from other members of its same class or from its friend classes.

ii. Protected members are accssible rom members of the same class and friend classes and also from the members of its derived classes.

iii. Finally, public members are accssible from anywhere where the class is visible.

Example:

class Newclass

{

int x,y; //private by default

public:

void set_value(int, int);

int add(void);

} ted;

In the above example, the class Newclass and an object called ted of this class type are declared. This class contains four members: two variables of type int ( x and y) in the private section (because private is the default permission) and two functions in the public section: set_value() and add(). of which we have included only the prototype.

HOME LEARN C++ PREVIOUS NEXT