C++ Classes and Objects

Classes in C++:

A class is a way to bind the data and its associated functions together. It allows the data and functions to be hidden, if necessary from external use. When defining a class, we are creating a new abstract data type that can be treated like any other built-in data type. A class specification has two parts:

1. Class declaration

2. Class function definitions

Class declaration:

The class declaration describes the type and scope of its members. It has the following Syntax:

class class-name
{
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};

Class function definitions:

The Class function definitions describe how the class functions are implemented.

Example:

class product
{
int number; // variable declaration
float cost; // variable declaration
public:
void getdata(int x, float y); // function declaration
void putdata(void);
};

Objects in C++:

In C++, the class variables are known as objects. Objects can also be created when a class is defined by placing their names immediately after the closing brace, as we can do in the case of structures.

Array of Objects:

An array can be of any data type including struct. Similarly, we also have arrays of variables that are of the type of class. Those variables are called Arrays of Objects.

Example:

class employee
{
char name[25];
int age;
public:
void getdata(void);
void putdata(void);
};

The identifier employee is a user-defined data type and it is used to create objects that relate to different categories of the employee.

Example:

employee manager[2];
employee worker[50];

The array manager contains two objects(manager) namely manager[0], and manager[1] of type employee class. Similary the worker array contains 50 objects(worker) namely worker[0], worker[1], worker[2], worker[3], worker[4] ,…….., worker[50] of type employee class..