Page 78 - DCAP404 _Object Oriented Programming
P. 78
Unit 4: Classes and Objects
private functions. However, the public members (both functions and data) can be accessed from Notes
outside the class. The binding of data and functions together into a single class-type variable is
referred to as encapsulation. The access to private and public members of a class is well explained
diagrammatically in the Figure 4.1.
Let us consider the following declaration of a class for student:
class student
{
private:
int rollno;
char name [20];
public:
void getdata(void);
void disp(void);
};
The name of the class is student. With the help of this new type identifier, we can declare
instances of class student. The data members of this class are int rollno and char name [20]. The
two function members are getdata() and disp(). Only these functions can access the data members.
Therefore, they provide the only access to the data members from outside the class. The data
members are usually declared as private and member functions as public. The member functions
are only declared in the class. They shall be defined later.
Task The binding of data and functions together into a single class-type variable is
referred to as encapsulation. Do you agree with this statement? Why or why not?
A class declaration for a machine may be as follows:
class machine
{
int totparts, partno;
char partname [20];
public:
void getparts (void);
void disp(part_no);
};
Having defined the class, we need to create object of this class. In general, a class is a user defined
data type, while an object is an instance of a class. A class provides a template, which defines the
member functions and variable that are required for objects of a class type. A class must be
defined prior to the class declaration.
The general syntax for defining the object of a class is:
class <class_name>
{
LOVELY PROFESSIONAL UNIVERSITY 71