Classes and Objects
Classes and Objects
classes and
objects
What is class
A class is an user defined data type.
It contains the data variables and functions.
It is a way to bind the data and its associated
functions together.
It allow data and functions to be hidden from
outside world, if necessary.
The class declaration describes the type and
the scope of its members.
Continue
Class definition:
class class_name
{
public:
Variable declaration;
Function declaration;
private:
Variable declaration;
Function declaration;
};
Visibility modes
Public:
When any member (variable or function) is
defined as public then it is accessible from the out
side the class in which it is defined as well as from
the members of its class.
Private:
When any member (variable or function) is
defined as private then it is accessible only within
class in which it is defined and not from out side
the class.
Continue
By default the members of a class are private.
This type of a class is completely hidden from
the out side world.
The variables declared inside a class are called
member variables.
The functions declared inside a class are called
member functions.
Member functions are allowed to access the
private member variables of a class.
Continue
Simple class example
class item
{
private:
int num;
float cost;
public:
void getData(int a, float b);
void putData();
};
Creating objects
Objects are the variables of class data type.
Objects are declared inside the main()
function body.
Class declaration define only what it contain.
For example:
item x;
It creates a variable x of class item type and in c++ it
is called object of class.
Continue
We can create any number of object of a class
type. For example:
Item x,y,z,t,p;
Objects are also called an instance of a class.
Class declaration does not create any memory
space for the objects.
When objects are created, necessary memory
is created for that object.
Continue
Objects can also be created when class is defined by
placing their names immediately after the closing
brace such as:
class item
{
private:
int num;
float cost;
public:
void getData(int a, float b);
void putData();
} x, y, z, t, p;
Accessing class members
Member functions are accessed through
objects of class with dot operator (.), it has the
following form:
object-name.function-name(actual arguments);
For example:
x.getData(25,45.67);
x.showData();
Defining member function