What Is Class and Object
What Is Class and Object
A class is a user defined data type that allows us to bind data and its associated functions
together as a single unit. Thus class provides the facility of data encapsulation.
Class provides the facility of data hiding using the concept of visibility mode such as public,
private and protected.
Once a class is defined we can create an object of the class to access variables and functions
defined inside the class.
Syntax:
class Class_Name
{
Private:
Data-Type Variable_Name;
Function declaration or Function Definition;
Public:
Data-Type Variable_Name;
Function declaration or Function Definition;
};
Class can be created using the class keyword. The class definition starts with curly bracket and
ends with curly bracket followed by semicolon.
We can declare variables as well as functions inside the curly bracket as shown in the syntax.
The variables defined inside class are known as data member and the function declared inside
the class are known as member function.
In order to provide data hiding facility class provides the concept of visibility mode such
as private, public or protected. If you don’t specify any visibility mode for the member of the
class then by default all the members of the class are considered as private.
The data member and member function declared as a public can be accessed directly using the
object of the class. But the data member and member function declared as private can not be
accessed directly using the object of the class.
Example:
class test
{
int a, b;
public:
void input ();
{
cout<<"Enter Value of a and b";
cin>>a>>b;
}
void output ()
{
cout<<"A="<<a<<endl<<"B="<<b;
}
};
There are two different methods for creating objects of the class:
(1) We can create object at the time of specifying a class after the closing curly bracket.
Example:
Class test
{
int a,b;
public:
void input ();
void ouput ();
}t1,t2,t3;
Here, t1, t2 and t3 are the objects of class test.
(2) We can create object inside the main function using name of the class.
The general syntax for creating object inside main function is as below:
Class_Name Object_Name;
Example:
Test t1, t2, t3;
Here, t1, t2 and t3 are the objects of class test.
Example:
class Test
{
int b;
Public:
int a;
void inputb()
{
b=20;
}
};
int main()
{
Test t1;
T1.a=10; //works because a is public
T1.b=20; //error because b is private
T1.inputb (); //works because inputb () is public
return 0;
}