Page 76 - DCAP404 _Object Oriented Programming
P. 76
Unit 4: Classes and Objects
You can think of a class as a data type; and it behaves like one. Just as a data type like int, for Notes
example, does not have a physical existence and does not occupy any memory until a variable of
that type is declared or created; a class also does not exist physically and occupies no memory
until an object of that class is created.
Example: To understand the difference clearly, consider a class of vehicle and a few
objects of this type as depicted below:
car
reg_no = DL2C2245
no_wheels = 4
fuel_type = PETROL
make = MARUTI
color = WHITE
vehicle scooter
reg_no; reg_no = DL2A1056
no_wheels; no_wheels = 2
fuel_type; fuel_type = PETROL
make; make = BAJAJ
color; color = CREAM
Class truck
reg_no = DL3D2259
no_wheels = 6
fuel_type = DIESEL
make = TATA
color = DARK ORANGE
Objects
In this example vehicle is a class while car, scooter and truck are instances of the class vehicle and
hence are objects of vehicle class. Each instance of the class vehicle – car, scooter and truck – are
allocated individual memory spaces for the variables – reg_no, no_wheels, fuel_type, make
and, color – so that they all have their own copies of these variables.
4.1 Specifying a Class
Like structures a class is just another derived data-type. While structure is a group of elements of
different data-type, class is a group of elements of different data-types and functions that operate
on them. C++ structure can also have functions defined in it.
There is very little syntactical difference between structures and classes in C++ and, therefore,
they can be used interchangeably with minor modifications. Since class is a specially introduced
data-type in C++, most of the C++ programmers tend to use the structures for holding only data,
and classes to hold both the data and functions.
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. Generally, a class
specification has two parts:
1. Class declaration
2. Class function definitions
The class declaration describes the type and scope of its members. The class function definitions
describe how the class functions are implemented. The general form of a class declaration is:
LOVELY PROFESSIONAL UNIVERSITY 69