Friday, May 11, 2007

Class & Objects


Class:
It is a basic block of Object Oriented Software.
Class is like a data type as struct in C. A datatype contains data and operations applicable to that data. We can take example of int data type, it contains data as well as operations like a+b , a-b , a*b etc.

In other words, class is a blueprint for objects. class decides what object can have and what task it can perform.

Now we will see, how class concept can be implemented through C++ -

General Form of Class

class
{
data member;

member functions;

};
// ; is must here

Example :

class Circle
{
int radius;

int GetRadius();
void SetRadius(int);
int CalculateArea(int);
};
:

In above example , we have seen how a class look like .
As we know by default, all members of class have private access-specifier. So in above class Circle, all the members will be private,means they can not be accessed from outside the class.Before discussing further, first we have a idea regarding Access Specifier :-

Access-Specifier : also known as visibility labels.
There are three types of Access specifiers

private : private members can be accessed only within the class itself.
public : public members can be accessed from outside the class also.In this case, member is fully exposed to outside-world.
protected : can be access from derived class only.(We will discuss this in detail during inheritance topic)

Now again we take above example. none of the member can be accessed from outside of the class, now to make some member accessible from outside we make one little but very important modification -


class Circle
{
int radius;

public:
int GetRadius();
void SetRadius(int);
int CalculateArea(int);
};
:

Now, to use this definition of class , Let's understand What is Object?