Shree Swaminarayan College c
of Computer Science %
“¥
Bsc i+
$
a
+
+
Unit -1
Fundamental of Programming and
QOP Concept
' PREPARED BY:
MADHAYV K. DAVE« Shree Swaminarayan College of Computer Science**¥z 4
B.Sc. IT - 3
CC-304, Programming in C++ Jun} =
5 Basic Concepts of Object Oriented Programming ?
It is necessary to understand some of the concepts used extensively in object —
oriented programming. These include:
(1) Objects
2) Classes
@) Encapsulation
(4) Data Abstraction
(8) Inheritance
(6) Polymorphism
(7) Dynamic Binding
(8) Message Passing
1. Objects:- \
* Objects are the basic run-time entities in an object — oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the
program has to handle.
‘ They may also represent user defined data such as vectors, time and lists.
‘ Programming problem is analyzed in terms of objects and the nature of
communication between them,
“+ Program objects should be chosen such that they match closely with the real-world
objects.
* Objects take up space in the memory and have an associated address like a record in
Pascal, or a structure in C.
‘+ When a program is executed, the objects interact by sending messages to one another.
For example, if “customer” and “account” are two objects in a program, then the
customer object may send a message to the account object requesting for the bank
balance.
“Each object contains data and code to manipulate the data.
% Objects can interact without having to know details of each other's data or code, It is
sufficient to know the type of message accepted, and the type of response retuned by
the objects. Although different authors represent them differently. below figure shows
‘wvo notations that are popularly used in object-oriented analysis and design,
Prepared By: - Madhav K. Dave (SSCCS, Bhav
Page 1 of 42of Computer Science”4° 7°92
<
(a)
‘
y
rs
DATA
Name
Date-of-birth
Marks
FUNCTIONS
Total
Average
Display
2. Classes:-
ta. The entire set of data and code
“Object contain data, and code
of an object can be made a user-defined data type with the help of class. In fact,
to manipulate that dat
objects are variables of the type class.
Once a class has been defined, we can create any number of objects belonging to that
Jass with which they are created.
class.
mango, apple and
Each object is associated wit
‘A class is thus a collection o}
orange are members of the class
Classes are user-defined data
programming language.
If fruit has been defined as a class,
fruit mango;
ate an object mango belonging to the class fruit.
template. It specifies what data and what
h the data of type cl
objects of similar type. For example,
fruit.
types and behave like the built-in types of @
then the statement is :
will cre
‘A class serves as a blueprint or a plan or a
be included in objects of that class.
s its format and behavior by defining a class. For example,
fined data type to represent dates. The compiler and the
functions will
“The programmer define
there can be a user-de!
computer do not know about dates.
‘Programmers have to define the behavior of dates by designing a date class. This class
expresses the format of date and the operations that can be performed on it.
Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 2 of 42< EO Shree Swaminarayan College of Computer Science>
CC-304, Programming in C++
3. Encapsulation:
The wrapping up of data and functions into a single unit (called class) is known
as Encapsulation.
Encapsulation is a programming mechanism that binds together code and the data it
manipulates, and that keeps both safe from outside interference and misuse.
Data encapsulation is the most striking feature of a class. The data is not accessible to
the outside world, and only those functions which are wrapped in the class can access
it.
These functions provide the interface between the object’s data and the program. This
insulation of the data from direct access by the program is called data hiding or
information hiding.
In an object-oriented language, code and data can be bound together in such a way that
a self-contained black box is created. Within the box are all necessary data and code.
‘When code and data are linked together in this fashion, an object is created. In other
words, an object is the device that supports encapsulation.
Data Abstraction:-
Abstraction refers to the act of representing essential features without including
the background details or explanations.
Classes use the concept of abstraction and are defined as a list of abstract attributes
such as size, weight and cost, and function to operate on these attributes.
‘They encapsulate all the essential properties of the objects that are to be created.
‘The attributes are sometimes called data members because they hold information.
The functions that operate on these data are sometimes called methods or member
functions.
Since the classes use the concept of data abstraction, they are known as Abstract Data
Types.
Inheritance:.
Inheritance is the process by which objects of one class acquire the properties of
objects of another class.
+ Using a concept called inheritance new classes can be built from the old ones.
“ The new class referred to as a derived class, can inherit the data structures and
functions of the original class, or the base class.
The new class can add data elements and functions to those it inherits from its base
class.
Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 3 of 42ae See Shree Swaminarayan College o
ic pse.IT=3" (onic
sion. For example, the bird ‘robin’ is a
CC-304, Programming In CHF
‘concept of hierar
whicl
tical classific
Jn is again a part of the cla
his sort of division is that each derived class a ne
Jass from which it is derived as illustrated in below figure.
sss ‘bird’. 2
‘It supports the ie
part of the class ‘flying bird
4p The principal behind 1
characteristics with the cl
Attributes
Feathers
Lay eggs
Attributes
Attributes
Kiwi
Penguin
Swallow
Robin
Attributes
Attributes
Attributes
Attributes
[Property Inheritance]
‘In OOP, the concept of inheritance provides the idea of reusability. This means that ~~
we can add additional features to and existing class without modifying it. This is
possible by deriving a new class from the existing one.
The new class will have the combined features of both the classes.
The real application and power of the inheritance mechanism is that it allows the
programmer to reuse a class that is almost, but not exactly, what he wants, and in such
a way that it does not introduce any undesirable side effects into the rest of the classes.
Using inheritance, an object need only define those qualities that make it unique
within its class. It can inherit its general attributes from its parent. Thus, it is the
Page 4 of 42
Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar)Shree Swaminarayan College of Computer Science*¥4"7
B.Sc, IT=3"
CC-304, Programming in C++ ni
inheritance mechanism that makes it possible for one object to be a specific instance
ofa more general case.
6. Polymorphism:-
* Polymorphism is another important OOP concept. Polymorphism, a Greek term,
means the ability to take more than one form.
‘> An operation may exhibit different behaviors in different instances. The behavior
depends upon the types of data used in the operation,
“ For example, consider the operation of addition for two numbers; the operation will
generate a sum. If the operands are strings, then the operation would produce a third
string by concatenation. To exhibit different behaviors in different instances is known
as operator overloading.
> Figure:
Circle object Box object ‘Triangle object
ences
4 Above figure shows that a single function name can be used to handle different
number and different types of arguments. This is something similar to a particular
word having several different meanings depending on the context.
> Using a single function name to perform different types of tasks is known as function
overloading.
<> Polymorphism plays an important role in allowing objects having different intemal
structure to share the same external interface and is widely used to implementing
inheritance.
Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 5 of 42Swaminan json una
a
ceed by the phrase “one,
Te to design @ generic
s often expres
304. programming inc
it is possibl
the concept of polymorphism }
je methods.” This means that
elated activities.
.e complexity
More generally»
interface, mnultipl
interface to 9 group ofr
4 Polymorphism helps rede
general class of action.
by allowing the same interface to specify @
7. Dynamic Binding:-
ii yonse
Binding refers to the linking of a procedure call to the code to be executed in resp
to the call. ‘ ' .
Dynamic binding (also known as late binding) means that the code associated with @
given procedure call is not known until the time of the call at run-time.
Dynamic binding is associated with polymorphism and inheritance.
associated with a polymorphic reference depends on the dynamic
reference.
‘> Itis algorithm is, however, unique to each object
redefined in each class that defines the object. At run-tims
object under current reference will be called.
‘A function call
type of that
t and so the draw procedure will be
fe, the code matching the
8. Message Passing:-
4 An object oriented program consists of a set of objects that communicate with each
other.
4 The process of programming in an object-oriented languages therefore, involves the
following basic steps:
(1) Creating classes that define objects and their behavior.
2) Creating objects from class definitions, and
G) Establishing communication among objects.
é Objects communicate with one another by sending and receiving information much
the same way as people pass messages to one another.
% The concept of message passing makes it easier to talk about building systems that
directly model or simulate their real-world counterparts.
A nee for an object is a request for execution of a procedure, and therefore will
invoke a function (procedure) in the receiving obj ‘
g object that generates the desi
~ a nt red result.
4+ Message passing involves specifying the name of the object, the name of th Er
(message) and the information to be sent. For Example : : oe ee
Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 6 of 42
age 6 o!wee
S Sng & Shree Swaminarayan College of Computer Science? #3"
BSc. IT = 3"
CC-304, Programming in C+
employee.salary (name);
object information
message
Introduction of Function:-
A function is a subroutine that contains one or more C++ statements and performs a
specific task.
“> Every program that you have written so far has used one function: main( ). They are
called the building blocks of C+ because a program is a collection of functions.
“User-defined function as one of the main building blocks of C++ programs. A function
provides a convenient way of packaging a computational recipe, so that it can be used
as often as required.
Advantages of using functions are that it is possible to reduce the size of a program by
calling and using them at different places in the program.
+ All of the “action” statements of a program are. found within functions. Thus, a
function contains the statements that you typically think of as being the executable
part of a program. In fact, a large, commercial program will define hundreds of
functions.
“When the function is called, control is transferred to the first statement in the function
body. The other statement in the function body is then executed and control retumns to
the main program when the closing brace is encountered.
+> A function definition consists of two parts : Prototype(interfate) and body.
+ C++ function can be overloaded to make it perform different tasks depending on the
arguments passed to it.
© General form of a Function:-
& AllC-++ functions share a common form, which is shown here:
return-type func
{
n-name(parameter-list)
J body of function
Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 7 of 42SBE te Shree Swaminarayan College of Computer Science,
x* B.Sc. IT-3" aa
CC-304. Programming in CH ”
© Main Function in C++:
‘+ In C+, the main( ) retums a value of type int to the operating system. C++,
therefore, explicitly defines main() as matching one of the following
prototypes :
int main();
int main(int arge, char * argy[]);
‘* The functions that have a return value should use the return statement for
termination. The main( ) function in C++ is, therefore, defined as follows:
int main()
{
return 0;
*® The retum type of functions is int by default, the keyword int in the main ( )
header is optional. Most C++ compilers will generate an error or warning if
there is no return statement. C+ issues the warning :
Function should return a value
“© Many operating systems test the return value (called exit value) to determine if
there is any problem.
“% The normal convention is that an exit value of zero means the program runs
successfully, while a nonzero value means there was a problem. The explicit
use of a retum (0) statement will indicate that the program was successfully
executed.
e Function Prototyping:-
+ Function prototyping is one of the major improvements added to C++ functions.
“The prototype describes the function interface to the compiler by giving details
such as the number and type of arguments and the type of return values,
With function prototyping, a template is always used when declaring and defining
a function.
% When function is called, the compiler uses the template to ensure that proper
arguments are passed, and the return value is treated correctly.
Prepared By: - Madhav K. Dave (SsCcs, Bhavnagar)
Page 8 of 42 ‘‘arayan College of Computer Science? ¥4"
CC-304. Programming in C++ l
Any violation in matching the arguments or the return types will be caught by the
compiler at the time of compilation itself.
In C++, all functions must be declared before they are used. Typically, this is
Accomplished by use of a function prototype. Prototypes specify three things
about a function:
© Its retum type
© The type of its parameters
© The number of its parameters
+ Prototypes allow the compiler to perform three important operations:
© They tell the compiler what type of code to generate when a function is
called, Different retum types must be handled differently by the compiler.
They allow C+ to find and report any illegal type conversions between the
types of arguments used to call a function and the type definition of its
parameters.
© They allow the compiler to detect differences between the number of
arguments used to call a function and the number of parameters in the
function.
+ The function prototype is a declaration statement in the calling program and is of
the following form:
‘Syntax: - type function-name(argument.
4b The use of parameter names in a prototype is optional. The argument-list contains
the types and names of arguments that must be passed to the function.
Example: - float sum(float x, float y);
In the function declaration, the names of the arguments are dummy variables and
therefore, they are optional. That is, the form
float sum(float, float);
The above function prototype is acceptable at the place of declaration. At this
stage, the compiler only checks for the type of arguments when the function is
called.
+ Ingeneral, we can either include or exclude the variable names in the argument list
of prototypes.
4 The variable names in the prototype just act as placeholders and, therefore if
names are used, they don't have to match the names used in the function call or
function definition.
+> In the function definition, names are required because the arguments must be
referenced inside the function.
Prepared By: - Madhav K. Dave (SSCS, Bhavnagar) Page 9 of 42¢ Shree Swaminarayan College of Computer Science**;
BSc. IT—3" :
CC-304. Programming in C++ *
“> For Example,
float sum(float a, float b) .
{
float ans = atb;
}
‘> The function sum() can be invoded in tha program as follows:
float ans1=sum(x, y); // Function call
‘> The variable x and y are known as the actual parameters which specify’ the
dimensions of ansl. Their types should match with the types declared in’ the
prototype. Remember, the calling statement should not include type names in the
argument list.
* We can also declare'a function with an empty argument list, as in the following
example:
void display(void);
« Call by Reference
“A function call passes arguments by value. The called function creates a new set of
variables and copies the values of arguments into them.
“+ The function does not have access to the actual variables in the calling program
and can only work on the copies of value.
‘ This mechanism is fine if the function does not need to alter the values of the
original variables in calling program but there may arise situations where we
would like to change the value of variables in the calling program.
~ For example, in bubble sort, we compare two adjacent elements in the list and
interchange their values if the first element is greater than the second.
If a function is used for bubble sort, then it should be able to alter the values of
variables in the calling function, which is not possible if the call-b-value method is
used.
Provision of the reference variables in C++ permits us to pass parameters to the
functions by reference.
When we pass arguments by reference, the ‘formal’ arguments in the called
function become aliases to the ‘actual’ arguments in the calling function.
This means that when the function is working with its own arguments, it is
actually working on the original data.
Consider the following Function:
&
*
”
Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 10 of 42a7
* See Shree Swaminarayan College of Computer Science?”
BSc. IT [ean]
CC-304. Programming in C+ l
void swap (int &a, int &b) // a and b are reference variables
{
Ay
“ee
int t= 95
a=b;
b
I
4 Ifm and n are two integers variable then the function call :
swap(m , n)
+ Will exchange the value of m and n using there aliases (referehce variables) a and
b. this is accomplished using pointer and indirection as follows:
void swap! (int *a , int *b) / function definition
{
int t5
t=*a; —_//assign the value at address ato t
* // put the value at b into a
*b=*t; // put the value at t into b
}
‘ This function can be called as follows:
swapl(&x,&y); _ //call by passing addresses of variables
Return by Reference
A function can also retumn a reference. Consider the following function:
int & max (int &x, int &y)
{
if(x>y) '
{
return(x);
} '
return(y);
Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 11 of 42~25_.£ Shree Swaminaray@)
* RY f
CC-304. Programming in C++
Since the return type of main( ) is int & the fu
(and not the values). Then @ function call such as
either a or b depending on their value. , .
‘This means that this ‘fanetion call can appear on the left-hand side of assignment
statements. That is, the statement.
max(a, b) =15
‘This is legal and assigns -1 to a ifitis lar
A Inline Function i
in a program is to save some memory
One of the objectives of using function
space, which becomes appreciable when a function is likely to be called many
times.
«» However, every time a function is called it takes 2 Jot of extra time in exec
series of instructions for takes such as jumping to the function, saving registers,
pushing arguments into the stack and returning the callirig function.
“ When a function is small, a substantial percentage of execution time may be spent
in such overheads.
One solution to this problem is to use macro definitions, popularly known as
macros; Preprocessor macros are popular in C.
«> The major drawback with macros is that they are not
the usual error checking does not occur during compilation.
Cat has a different solution to this problem. To eliminate the cost of calls to small
functions, C++ proposes a new feature called Inline Function.
An Inline Function is a function that is expanded in line when it is invoked.
& That is, the compiler replaces the function call with the corresponding function
code (something similar to macros expansion).
+ The inline functions are defined as follows :
puter Science? 7;
n College of Com|
34
Unit
rnetion returns reference to X ory
max(a,b) will yield areference to *
ger, otherwise -1tob.
ating a
really function and therefore,
Syntax:-
inline function-header
{
}
funetion body
Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 12 of 42 ofCC-304. Programming in C++
n College of Computer Sciene:
m
Mat
Shree Swaminaray:
Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 13 of 42
BHO
Example:-
inline int mul(int x, int y)
{
return (x*y)3//20
main()
{
cout<
Some of the situations where inline expansion may not work are:
1. For functions returning values, if a loop, a switch or a goto exists.
2. For functions not returning values, if a return statement exists.
3. If functions contain static variables.
4, If inline functions are recursive.
Default Arguments
& C+ allows us to call function without specifying all its arguments. In such cases,
the function assigns a default value to the parameter which does not have a
matching argument in the function call.
Default value are specified when the function is declared. The compiler looks at a
i
prototype to see how many arguments a function uses and alerts the programs for
possible default values.
Syntax:
type function-name(argument-list, default-argument);7 Shree Swaminarayan College of Computer Science»;
: BSc. IT-3"
CC-304, Programming in C+
Example:-
int sum(int a, int b, int c=4);
+ The above prototype declares a default value of 4 to the argument c.A subsequent
funetion call like :
value = sum(5,8); // one argument missing
To override default value we passes an explicit value like :
value = sum(5,8,9);
The default value is specified in a manner syntactically similar to a variable
initialization.
‘+ A default argument is checked for type at the time of declaration and evaluated at
the time of call.
One important point to note is that only trailing arguments can have a default
values and therefore we must add default form right to left.
Some examples of function declaration with default value are:
t mul (inti, intj=5,k= 10); // legal
int mul (int i= 0, int j, int k= 10); // illegal
int mul (int i=5, int j); H illegal
Benefits of Default Argument
* Default arguments are useful in situations where some arguments aly ys have the
same value,
For example, bank interest may remain the same for all customers for a particular
period of deposit.
It also provides a greater flexibility to the programmers.
A function can be written with more parameters than are required for its most
common application.
Using default arguments, a programmer can use only those arguments that are
meaningful to a particular situation.
%
*
‘We can use default arguments to add new Parameters to the existing functions.
Default arguments can be used to combine similar functions into one.
¢ Const Arguments
In C++ an arguments to a function can be declared as const as shown below:
int sttrlen( const char *p);
int langth (const string &s);
Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 14 of 42ME
Ske « Shi i a
Steed ree Swaminarayan
College of Computer Science? ¥4"7
A structure is a convenient tool for handin; ; :
s a group of logically related data i
p + Ibis a user-defined data type with a template that serves to define its dat —-
. :
Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar)
Page 16 of 42 /SSE Shree Swaminarayan College of Computer Science?“
B.Sc, IT- 3 7
CC-304. Programming in C++ [[enie—1 J
% Once the structure type has been defined, we can create variables of that type using
declarations that are similar to the built-in type declarations.
“+ For example, consider the following declaration:
t struct student
{
char name|20};
int rollno;
float percentage;
i
& The key-word struct declares student as a new data type that can hold three fields of
different data types.
“These fields are known as structure members or elements.
+> The identifiers student, which is referred to as structure name or structure tag, can be
used to create variables of type student.
* Foreg,
struct student S; // C declaration
+ S is a variables of type student and has three member variables as defined by the
template, Member variables can be accessed using the dot or period operator as
follows:-
strepy(S.name, “madhav");
S.rolino = 35;
S.percentage = 75.86;
¢ Limitations of a C structure
“> The standard ¢ does not allow the struct data type to be treated like built-in data types.
For example, consider the following structure:
struct complex
{
float x;
float y; \
b i
struct complex c1,¢2,c3; i
“ The complex number cl, c2 and c3 can easily be assigned values using the dot
operator but we can not add two complex numbers or subtract one from the other. For
eB,
Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 17 of 42of Computer Science? ¥;
eo 2c 2 Shree Swaminarayan College
Ge pseiT-3
CC-304. Programming in C++
eeclte2; // Its illegal
imitation 0!
in C Language
{fc structures is that they do
accessed by the structur
not permit data hiding
+ Another important li a nembers are public
structure members can be directly
members.
Extensions to structures
C++ supports all the features of structures as defined in c. but C++ has expanded its
capabilities further to suit its OOP philosophy.
> It attempts to bring the user-defined types as ¢
types, and also provides a facility to hide the data
of OOP.
Inheritance a mechanism by which one type can inherit characteristics from other
types is also supported by C++.
In C++, a structure can have bot!
declare some of its members as ‘private’ so that the;
Jose as possible to the built-in--data
which is one of the main principles
.s members. It can also
h variables and functions @:
be accessed directly by
y can not
*
the external functions.
In C++, the structure names are stand alon
In other words, the key-word struct can
variables. For example, we can declare the st
Student S; // C++ declaration
Remember, this is an error in e.
4 C++ incorporates all these extensions in another user-defined type known as class.
‘There is very little syntactical difference between structures and classes in C++ and,
therefore, they can be used interchangeably with minor modifications.
a 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
functions.
an be used like any other type names.
e and c:
leclaration of structure
be omitted in the de
student variable S as :
¢ Specifying a Class
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:
0 1.Class declaration
) o 2.Class function definitions
4
5
>
3 Prepared By: - Madh: a
n0,02 yy: - Madhav K, Dave (SSCCS, Bhavnagar) Page 18 of 42B.Sc. IT = 3" -
CC-304. Programming in C++ [Lunit—3 |
~- Shree Swaminarayan College of Computer Science*¥7~
The general form of a class declaration is:
class class-name
{
private:
data member;
member function;
public:
data member;
member function;
The class declaration is similar to a struct declaration. The key-word class specifies
that what follows is an abstract data of type classname.
The body of a class'is enclosed within braces and terminated by a semicolon, The
class body contains the declaration of variables and functions.
These functions and variables are collectively called class members.
They are usually grouped under two sections, namely, privates and public to denote
which of the members are private and which of them are public.
The key-words private and public are known as visibility labels. Note that these key-
words are followed by a colon.
The class members that have been declared as private can be accessed only from
within the class.
On the other hand, public members can be accessed from outside the class also. The
data hiding (using private declaration) is the key feature of object-oriented
programming.
‘The use of the key-word private is optional. By default, the members are private. Such
a class is completely hidden from the outside world and does not serve purpose.
The variables declared inside the class are known as data members and the functions
are known as member functions. i
Only the member functions can have access to the private data members and private
functions.
However, the public members (both functions and data) can be accessed from outside
the class.
The binding of data and functions together into a single class-type variable is referred
to as encapsulation.
A simple class example:-
Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 19 of 42. oe ee
ience* 75-34
#
[ou ,
ge of Computer Se
vd
eee te Shree
‘ * \
CC-304. Programming in C++
% A typically class declaration would look like:
class item
‘ int number; ivariables declaration private by default
float cost;
public:
void getdata(int a, float b); function declaration using prototype
void putdata( );
‘ Hends with semicolon
such as item. This name now
be used to declare instances of that class type.
bers and two function members. The data
ction ate public by declaration.
ember variables number
We usually give a class some meaningful name,
becomes a new type identifier that can
‘> The class item contains two data mem!
members are private by default while both the fu
to assign values to the m:
The function getdata() can be used
and cost, and putdata( ) for displaying thei
These functions provide the only access to
This means that the data can not be accessed by any
class item.
Note that the functions are detlared, not defined. Actual function defini
appear later in the program.
‘The data members are usually declared as private and the member functions as
For following figure shows two different notations used by the OOP analysts to
represent a class :
°
ir values.
the data membs
function that is not a me!
ers from outside the class.
ember the
*
+o
itions will
public,
*
getdata()
putdata( )
FUNCTIONS
getdata( )
putdata()
[Representation of a class]
Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 20 of 42Stoo Shree Swaminarayan College of Computer Science
B.Sc. IT- 3
;
ae
CC-304, Programming in C++
Or
a
* Creating objects:~
* Remember that the declaration of item as shown above does not define any objects of
\ ‘q,_tem but only specifies what they will contain,
* Once a class has been declared, we can create variables of that type by using the class
name (like other built-in type variable). For example,
item x; // memory for x is created
* Creates a variable x and of type item.
% In C++, the class variables are known as objects. Therefore, x is called an object of
type item. We may also declare more than one object in one statement. For example,
item x, y, z 5 // three objects created
*% The declaration of an object is similar to that of a variable of any basic type. The
necessary memory space is allocated to an object at this stage. Note that class
specification, like a structure, provides only a template and does not create any
memory space for the objects.
Objects can also be created when a class is defined by placing their names
immediately after the closing brace, as we do in the case of structures. That is to say,
the definition :
class item’
Would create the objects x, y and'z of type item. This practice is seldom followed
because we would like to declare the objects close to the place where they are used
and not at the time of class definition.
© Accessing class member: '
‘> The private data of a class can be accessed only through the member functions of that
class. The main( ) can not contain a statements that access number and cost directly.
is the format for calling a member functions:
the followi
For example, the function call statement
x.getdata(50,75.5); // It is valid
It assigns value to private data member of a class implementing the getdata( ) function.
°
+ Similarly, the statement :
x.putdata( );
L Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar). ' Page 21 of 42
REO P2¢ Shree Swaminarayan College 9 4
. r-3" ae is
CC-304. Programming in C++ : ‘
wes of data members. Remember, 2 member function can be J
Would display the val
invoked only by using a
“> The statement
x.number=100;
4 Is also illegal. although x is an object oF
number (declared private) can be accessed 0
the object directly. ;
Itmay be recalled that objects communicate by sending and receiving
is achieves through the member functions.
“A variables declared as public can be accesse
n object (of the same class).
ich number belongs, the
f the type item to whic
i ter function and not by
nly through a mem
messages. This
.d by the objects directly.
© Foreg., class xyz
{
private: .
int x;
int ¥5
public:
int 25
ys
void main()
{
11 error, x is private
p.z=10; /ok, z is public
geteh0;
Defining member functions:-
‘Member functions can be defined in two places:
(1) Outside the class definition.
(2) Inside the class definition.
¢b It is obvious that, irrespective of the place of definition, the function should perform
the same task. Therefore, the code for the function body would be identical in both the
cases, However, there is subtle difference in the way the function header is defined
(1) Outside the class definitior
“+ Member functions that are declared insi
sid ve 5 .
the class. ide a class have to be defined separately outside
Pi So
repared By: - Madhav K. Dave (SSCS, Bhavnagar) Page 22 of 42CC-304. Programming in C++
Shree Swaminarayan College of Computer Science?*¥474- a)
Sc. I rd
[oa]
aie
% Their definitions are very much like the normal functions. They should have a yeh
function header and a function body. Since et does not support the old version of | 7
function definition, the ANSI prototype form must be used for defining the function
header.
% An important difference between a member function and a normal function jis that a
.__ Member function incorporates a membership ‘identity label’ in the header.
‘© This ‘label’ tells the complier which class the function belongs to. The general form of
a member function definitions is:
return-type class-name ;: function-name(argument declaration)
{
function body
}
‘ The membership label class-name :: tells the compiler that the function function-name
belongs to the class class-name. That is, the scope of the function is restricted to the
class-name specified in the header line. the symbol :: is called the scope resolution
operator.
‘ For instance, consider the member functions getdata() and putdata() as discussed
above topics, they may be coded as follows:
void item
{
etdata(int a, float b)
number = a;
cost = b;
}
‘ Since these functions do not retum any value, their retum-type is’ void. function
arguments are declared using the ANSI prototype.
“ The member functions have some special characteristics that are often used in the
program development. these characteristics are:
1. Several different classes can use the same function name. The ‘membership label”
will resolve their scope.
2. Member functions can access the private data of the class. A non-member function.
can not do so. (However, an exception to this rule is a friend function discussed
later).
3. A member function can call another member function directly, without using the
dot operator.
Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 23 of 42: puter Science*+;, aan
24. Shree Swaminarayan %
pseIt=3° (oma,
inC+
lace the function declaration
Je, we could define the item
College of Com!
T-3"
CC-304. Programming
(2) Inside the class definition:-
Another method of defining a member function is to repl
by,the actual function defining inside the class. For examp!
class as follows:
class item
{
int number; ‘
float cost; :
public:
void getdata(int a, float b); ‘//Member function declaration
J Inline fanciton
void putdata(void) // definition inside the class
{
cout< A data mem!
variable are
special character
© It is initial
initialization is permitted
Only one copy of that member i
ail the objects ofthat class, no matter how PUY
9. Itis visible only within the class, but its lifetime is
Static variables are normally used to maintain values common:
The definition of static data member is as follows :
Synta2 type class-name static-variables &
count;
s class is created. No other
fe first object of it
oe
Example:- int item ,
‘Note that the type and scope of each static member variable must be defined outside
definition.
.d separately rather than as a
“se This is necessary because the static data members ar° store
part of an object.
oe Since they are associ
are known as class variabl
4 The static variable count is initiaiz
“The count is incremented whenever th
*
ated with the class itself rather than with any class object, they
fed to zero when the objects are created.
data is read into an object.
f variable is shared by all the objects.
f+ Static data member is only one copy o
‘ber functions as they are declared in a class
“ Static variables are like non
declaration and defined in the source file.
‘* While defining static variables, some initial
1 value can also be assigned to the
variables.
¢ For instance, the following definition gives count the initial value 10.
int item :: count = 10;
hati member functions:~
‘ Like static member variabl
: nember variable, we can also have static mi
function that is declared static has the following a sae Seats
© A static function can have access ly static members (functions of
Wve access to only othi
: er
‘ariables) declared in the same class. :
© A static member functior
: mn can be ci i
objects) as follows: ae
class-name : : function-name(
Mad!
ladhav K. Dave (SSCCS, Bhavnagar)
1g the class name(instead of its
Prepared By:
Page 28 of 42« Shree Swaminarayan College of Computer Science*>
B.Sc. IT~3"
CC-304, Programming in CH (Luni
* Arrays of objects:-
> We
a < know that an array can be of any data type including struct. Similarly, we can also
fave arrays of variables that are of the type class. Such variables are called arrays of
objects. Consider the following class definition :
class employee
{
char name[30];
int age;
Public:
Void getdata(void);
Void putdata(void);
% The identifier employee is a user-defined data type and can be used to create objects
that relate to different categories of the employees. Example,
employee manager(3];_//array of manager
employee foremen[15}; //array of foremen
employee worker{75};_// array of worker
“ For above e.g. the array manager contains three objects(managers), namely,
manager{0], manager[1] and manager{2], of type employee class.
‘ Similarly, the foreman array contains 15 objects(foremen) and the worker array
contains 75 objects(workers).
Since an array of objects behaves like any other array, we can use the usual array
accessing methods to decess individual elements and the dot member operator to
access the member functions. For e.g. , the statement :
manager| i |.putdata( );
Will display the data of the i element of the array manager. That is, this statement
requests the object manager{i] to invoke the member function putdata( ).
‘ An array of objects is stored inside the memory in the same way as a multi-
dimensional array.
Member functions are stored separately and will be used by all the objects.
Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 29 of 42;
cts as function arguments:-
e Obje
ect may be used as @ function argument. this can be
“Like any other data type, an obj
done in two ways'=
re object is passed to the function.
o Acopy of the enti
rans
o Only the address of the object is ferred to the function.
is passed to the
Ge The first method is called pass by value. Since a copy of the object ;
function, any changes made to the object inside the function do not affect the object
used to call the function. The second method is called pass by reference. when an
address of the object is passed, the called funetion works directly on the actual objects
‘used in the call. This means that any changes ‘made to the object inside the function”
will reflect in the actual objects. The Pass by reference method is more efficient since
it requires passing only the address of the object and not the entire object.
“An object can also be passed as an argument to a non-member function.however; such
function can have access to the public member through the objects
functions only
passed as arguments to it. These functions can not have access to the private data
members.
Friendly Function:-
We have been emphasizing throughout this chapter that the private members cannot be
accessed from outside the class.
‘That is, a non-member function cannot have an access to the p!
However, there could be a situation where we would like two ¢
particular function.
For example, consider a case where two classes, manager and scientist, have been
defined.
& We would like to use a function income_tax() to operate on the objects of both these
rivate data of a class.
lasses to share a
*
%
classes.
In such situations, C++ allows the common function to be made friendly with both the
classes, thereby allowing the function to have access to the private data of these
o
classes.
Such a function need not be a member of any of these classes.
The function declaration should be preceded by the keyword friend. The function is
defined elsewhere in the program like a normal C++ function.
The function definition d i ie
m joes not use either the keyword friend or the scope operator
: Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 30 pe f« Shree Swaminarayan College of Computer Science?¥4~
; BSc. 1T- 3"
CC-304, Programming in C+
+ 5
% The functions that are declared with the keyword friend are known as “friend
functions”.
A function can be declared as a friend in any number of classes. A friend function,
athoush not a member function, has full access rights to the private members of the
class.
The friend functions are often used in operator overloading.
> A friend function possesses certain special characteristics:
tis not in the scope of the class to which it has been declared as friend.
Since it is not in the scope of the class, it cannot be called using the object of that
class.
It can be invoked like a normal function without the help of any object.
Unlike member functions, it cannot access the member names directly and has to
use an object name and dot membership operator with each member name. (¢-8.
Ax)
It can be declared either in the public or the private part of a class without
affecting its meaning,
Usually, it has the objects as arguments.
¢ Const Member Function
Ifa member function does not alter any data in the class, then we may declare it as
a const member function as follows:
void mul(int, int) const;
double get_balance() const;
‘The qualifier const is appended to the function prototypes (in both declaration and
definition). The compiler will generate an error message if such function try to alter the
data values.
© Pointers to Members
It is possible to take the address of a member of a class and assign it to a pointer.
‘The address of a member can be obtained by applying the operator & to a “fully qualified”
Prepared By: - Madhav K. Dave (SSCS, Bhavnagar) Page 31 of 42an College of Computer Science*¥z =f
‘4
2. Shree Swaminaray:
a pSe.IT-3"
BSE
g the operator ::* with
CC-304. Programming in C++
7 can be declared usin
Joss member name. A class member Po!ntc!
the class name.
Fore,
class A
{
private:
int m;
public:
‘void show 03
‘
We can define # pointer to the member m #8 follows:
int Avs" ip = &A = mj
er oreated thus acs like a class member in th
tatement above, the phrase Az"* means “Pointer-To-Mem!
the “address of the m member of A class”.
tatement is not valid:
won't work
‘as meaning only when it is
must be applied to both the
fat it must be invoked with a
ber of A class”.
The ip point
class object. In the st
‘The phrase &A::m means
Remember, the following st
int “ip = &m;
‘This is because m is not simply an int OPS data, It hi
associated with the lass to which it belongs. The scope operator
pointer and the member.
‘The pointer ip can now be used t0 208% the
dons), Let us assume that a is an obje=t 0
inter ip as follows:
mber m inside member function (or
mel
‘a member function. We
friend func fA declared in
can access m using the poi
cout << a.*ip;
cout << a.m;
II display
// same as above
Now, look at the following code:
ap = &a;
cout < “ip;
cout << ap > mi
->* is used to access a mem!
1g operator.* is used when the object
J/ ap is pointer to object a
1 display m
I] same as above
ber when we use pointer
itselfis
The dereferencing operator
‘ect and the member. The dereferencin;
that *ip is used like a member name.
ber functions which, then, can be invoked using
both the obj
used with the member pointer. Note
Dy We can also design pointers to mem
p dereferencing operators in the main as shown below:
Madhav K. Dave (SSCCS, Bhavnagar)
Prepared By:CC-304, Programming in C+
(oblectname ~* pointer-to-member function) (10);
‘i (Pointer-to-object ->* pointer-to-member function) (10);
‘The precedence of () is higher than that of * and ->*, so the parentheses are necessary.
© Local Class
Classes can be defined and used inside a function or a block. Such classes are
called local classes,
Void test (int a) J function
{
class student
I local class
11 class definition
create student object
student si(a);
Ihase student object
Local classes can use global variables (declared, above the function) and static
variables declared inside the function but cannot use automatic local variables. The global
variables should be used with the scope operator (::). '
t
‘There are some festrictions in constructing local classes. They cannot have static data
members and member functions must be defined inside the local classes. Enclosing function
cannot access the private members of a local class. However, we can achieve this by declaring
the enclosing function as a friend. He
. Dave (SSCCS, Bhavnagar) Page 33 of 42
Prepared By: - Madha'yer function such as
a we have used mem
mber variables,
ses of class implemental
ate met
In all the cas
getdata( ) and setvalue (
For e.g. the following statement:
S.input( );
) to provide initial values 10 the privs
Invokes the member function input which assigns the initial values to the data items of
object S. Similarly, the statement:
X.getdata( )5
function getdata( ), where these values a=
Passes the Initial values as arguments to the
assigned to the private variables of object *-
ments are Us priate objects that have
‘All these “functions call” stater ced with the approt
already been created.
rnnot be used to initialize the member variables at the time of
‘These functions ca
creation of their objects.
One uf the aims of C+ is to create user-defined data types such as class, which
behave very similar to the built-in types.
4} This means that we should be able to initialize a class type variable (object) when it is
able.
ich the same way as initialization of an ordinary vari
declared, mu
For example,
automatically destroys the variable. But it has not happened with the objects we have
so far studied.
It is therefor
re clear that some more features of classes need to be explored that would
enable us to initialize the objects when they are created and destroy them when thei!
rem when
presence is no longer necessary.
Prepa 2
pared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 34 of 42#
Bse.1t=3" re] a
cso sta Programming ince 7
“* C++ provides a special member function called the constructor which enables an Yt
object to initialize itself when itis created,
This is known as automatic initialization of objects.
% Italso provides another member function called the destructor that destroys the objects
when they are no longer required.
CONSTRUCTOR:
% A constructor is a ‘special’ member function whose task is to initialize the objects of
its class. It is special because its name is the same as the class name.
% The constructor is invoked whenever an object of its associated class is created.
Itis called constructor because it constructors the values of data member of the class.
“ A constructor is declared and defined as follows:
// class with a constructor
class integer
{
int m,n;
public:
integer( ); // constructor declared (Default or No argument)
integer :: integer() // constructor defined
{ ‘
m=0;
n=0;
+ When class contains a constructor like the one define above, it is guaranteed that an
object created by the class w
jtialized automatically. For example, the declaration
integer intl; ' // object intl created
Prepared By: - Madhav K. Dave (SSCS, Bhavnagar) Page 35 of 42yi -
ze of
swaminarayan College
ae Shree alta
ae
s data member's
n cH __—
cc-304, Programming I ak
ea Nor only ereates the object intt ofiype integer but also init ‘
fot only create
is
a to 2er0, /
raonl any statement to invoke the constructors function (as we do
fs 4 ‘There is no need to write
4 with the normal member function). ;
4 for zero intiatzation, we WOH need to
1° member functions is defines
invoke this function for each of the objects separately.
if there are a large number of objects.
This would be very inconvenient, ect
parameters is called theldefault cor jstracctor] The default
4 A constructor that accepts no
constructor for class A is A: :A()-
such constructor is defined, then the compil
“Ifa ‘normal
© Ifnos er supplies a default constructor.
‘Therefore a statement such as :
Aas
Invokes the default constructor of the compiler to ereate the object a.
CHARACTERISTICS OF CONSTRUCTOR: «
‘The constructor functions have some special characteristics like:
They should be declared in the public section.
+ They are invoked automatically when the objects are created.
+ They do not have retum types, not even void and therefore, and they cannot retu
values. :
Th i
ey cannot be inherited, though a derived class can call the base class constructo
r.
Like other e+ functions, they can have default arguments,
Constructors cannot be virtual.
+ We cannot refer to their address.
ae
An object with a constructor (or Destructor) cannot be used as a member of a union.
They make “implicit calls" to the operators new
Ww
‘i a
required, ind delete when memory allocation is
Prepared By: - Madhav - Dave (Ss av!
pared By: - Madhav K. Dave (ssccs, B
» Bh:
nagar) Page 36 of 42« Shree Swaminarayan Coll
lege of Computer Science”
CC-304. Programming in C4. a [ou]
PARAMETE
J RIZED Constructors:
°
ie
When it may be necessary to initialize
_ the various data element of different objects
different val
hue ; .
® when they are created. So, C++ permits us to achieve this
objective by passing arguments to th
'€ constructor function when the objects arc
created,
tructe
The constructors that can take <‘catguments.are.called parameterized constructors.
+ F
% For e.g. The constructor integer( ) may be modified to take arguments as shown
below :
class integer
{
int m,n;
public:
integer(int, int); //Parameterized constructor
h
integer :: integer(int x, int y)
{
m=x;
ney;
When a constructor has been parameterized, the object declaration statement such as :
integer intl;
May not work.
+ We must pass the initial values as arguments to the constructor function when an
object is declared. This can be done in two ways :
> By calling the constructor explicitly.
> By calling the constructor implicitly.
- Madhav K. Dave (SSCCS, Bhavnagar)
Prepared By: Page 37 of 42Example gs Example (0,90), 71 explicit
5 oft
Exarmplt (0, 90> Tmpliclt
B.Sc. IT- 3"
CC-304, Programming in C++
The following declaration illustrates the first method :
integer int1 = integer(0,100); // explicit call
‘% This statement creates an integer object intl and passes the values O and 100 to it,
‘The second is implemented as follows :
{integer int1(0,100); // implicit call
‘This method sometimes called the shorthand method, is used very often asi is shore,
Tooks better and is easy to implement,
‘* When the constructor is parameterized, we must provide appropriate arguments forthe
constructor,
MULTIPLE CONSTRUCTORS IN A CLASS:
* We can also declare and define more than one constructor in a class.
% For example,
class integer
{
int m,n;
publi : |
integer() // constructor with no argument or Default Constret,
integer(int a, int b) // constructor with two argument.
{
m=a;
Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 380receives one integer object as an argument, For example,
the declaration :
integer it;
Would automatically invoke the fi
statement:
rst constructor and set both m & n of il to zero. The
integer i2(20,40);
Would call the second constructor which will initialize the data member's m & n of 2
to 20 & 40 respectively. Finally, the statement:
"integer i3 (2);
Would invoke third constructor which copies the values of i2 into 13.
In other words, it sets the value of every data elements of i3 to the valufe of the
corresponding data elements of i2. ‘
* As mentioned earlier, such a constructor i called the copy constructor.
‘> When more than one constructor function is defined in a class, we say that the
constructor is overloaded.
_ Aonstructor WITH DEFAULT ARGUMENTS:
4 It is possible to define constructor with default arguments. For example, the
constructor complex () can be declaring as follow:
complex(float real, float imag=0);
+ The default value of the arguments imag is zero. Then, the statement
complex (5.0);
+ Assigns the value 5.0 to the real variable and 0.0 to imag(by default). However, the
statement:
complex ¢(2.0, 3.0);
4 Assigns 2.0 to real and 3.0 to imag. The actual parameter, when specified overrideas
the default, value, the missing arguments must be the trailing ones(right-to-left
assignment).
Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 39 of 42f Computer Science”
7 :A () and the default
x
inar: lege ©
. Shree Swaminar ayan iy eg
Sc.
FORO eR
in C++
CC-304. Programming The defaul
ae both thes
When called with no argument, it becomes & default constructor. When e
forms are used in class, it causes ambiguity for a statement such as
Aa;
(or AzA (int=0).
4 The ambiguity is whether to ‘call’ A:
DYNAMIC INITIALIZATION OF OBJECTS:-
alized dynamically too. That is to say, the initial value of an
«Class objects can be initi
object may be providing during run time.
One advantage of dynamic initialization is that we can provide various initialization
formats, using overloaded constructors.
ime depending
This provides the flexibility of using different format of data at run ti
upon the situation.
Consider the long term deposit schemes working in the commercial banks .the banks
provide different interest rates for different schemes as well as for different periods of
savestmen, A cory Consinuctost i6 @ membert functor
cohida. jnifiallze, gr object usta y
ory Consrrucrors:- anotier object of Heame
AMA
“ A copy constructor is used to declare and initialize an object from another object. For
eg,
integer i2(i1);
nto
Would define the object i2 and at the same time initialize it to the values of il
il.
* Another form of this statement is :
integer i2 = il;
+ The process of initializi
alizing through a copy constructor is known as copy initialization.« Shree Swami ee:
SS ‘waminarayan College of Computer Science*¥4"4
| B.Sc. IT ~ 3"
CC-304. Programming in C+. (oma 1a
[unie=a J Ke
“A copy constructer t: a
takes a referen ji
Ice to an objects ae Y
oe ajects of the same class as itsel! re
4
“ A reference variable hi ructor. We canni
as be
by "en used as an argument to the copy constructor. We cannot
pass the arguments by value to copy constructors,
& When no copy cor i
PY constructer is defined, the compiler supplies its own copy constructer.
A copy consti i i
A Copy constructor is a special type of overloaded constructor that is automatically
invoked when a copy of an object is required.
By default, when an object is passed to a function, a bitwise (that is, exact) copy of
that object is made and given to the function parameter that receives the object.
+ However, there are cases in which this identical copy is not desirable.
DYNAMIC CONSTRUCTOR:-
‘The constructors can also used to allocate memory while creating objects.
+ This will enables the system to allocate the right amount of memory for each object
when the objects are not of the same size, thus resulting in the saving of memory.
% Allocation of memory to objects at the time of their, construction is known as
“dynamic construction of objects”. The memory is allocated with the help of the new
operator.
CONST OBJECTS:
‘% We may create and use ‘constant objects using, const keyword before object
\\
declaration. For example we may create X as constant, objects of the class matrix as
follows:
const matrix X( m,n); 11 object X is constant
Any attempt to modify the values of m and n will generate compile time error.
A constant object can call only const member function.
‘As we known, a const member is a function prototype or function definition the
keyword const appears after the function’s signature.
‘ Whenever const objects try to invoke non-const member function the compiler
generates errors.
Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 41 of 42hg meee =
* EST! ‘RUCT! ‘ORS
x ae Acdestructor, 95 the NOME implies, is
js the same ®S the class
a constructor.
e a constructor the dest
atilde.
+ the class integer ¢a
Like
name but is preceded bY
& For eg. the destructor fo
integer () 13
fakes any arguments nO!
ed implicitly by the compiler UP
does it retum any value-
‘on exit from the program {© clean
a A destructor never t
It will be invok
no longer accessible.
ructors in a program
storage that is
since it releases memory SPA¢
4 tis good practice to declare dest
for future use.
> Whenever new is used to allo
.onstructors, We should use delete
‘cate memory in the c*
free that memory.
e defined |
discussed above may bi
‘For example the destructor for the matrix class
followed:
mamatrix ()
matrix
{
for(int i= 05 i