10EE664: OBJECT ORIENTED PROGRAMMING USING C ++

silkthrilledSoftware and s/w Development

Nov 18, 2013 (3 years and 6 months ago)

153 views

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
1


10EE664: OBJECT ORIENTED PROGRAMMING USING C ++

PART
-
A


UNIT
-
1

:PRINCIPLES OF OBJECT
-
ORIENTED PROGRAMMING: Review of Procedure
Oriented Programming, Basic concepts of Object Oriented Programming


Object, Class,
Encapsulation, Inheritance, Polymorphism; Benefits of OOPs, Applications of OOP’s. 4 Hours


UNIT
-
2 :
THE
BASIC LANGUAGE C++: A comparison of C and C++, Structure of C++
program with Class, Preprocessor directives, C++ Statements


Input/Output, Comments,
Tokens, Keywords, Identifiers, Constants, Data types


string, pointer, reference, boole,
enumeration, arr
ay, complex number; typedef names, type compatibility, type conversion,
qualifier


const, volatile; Operators in C++, Operator Precedence and Operator Overloading;
C++ expressions


New and Delete. 6 Hours


UNIT
-
3
:
FUNCTIONS IN C++: Introduction, The
main() function, Function prototype, Call
by reference, Return by reference, Inline functions, Default arguments, const Arguments,
Function Overloading, Friend and Virtual functions, pointer to functions.



8 hours


UNIT
-
4
:
CLASSES AND OBJECTS: Int
roduction


declaration and definition of a Class,
defining member functions, C++ program with a Class, Making an outside function Inline,
Nesting of member functions,Arrays within a class, Static data members, static member
functions, Objects


global & l
ocal objects, scope & lifetime, memory allocation for objects,
dynamically allocated objects, pointers to objects, arrays

of objects, function arguments with
objects, returning objects; const member functions.





8 Hours

PART
-
B

UNIT
-
5
:
CONSTRUCTORS AND

DESTRUCTORS: Introduction, Constructors,
Parameterized Constructors, Multiple constructors in a class, Constructors with default
arguments, Dynamic initialization of objects, Copy constructor, Constructing two
-
dimensional
arrays, const Objects, Destructor
s.








4 Hours


UNIT
-
6
:
OPERATOR OVERLOADING AND TYPE CONVERSION: Introduction,
Defining operator overloading, Overloading unary operators, Overloading binary operators,
Overloading binary operators using Friends, Rules for overload
ing operators, overloading a
comma operator, overloading the output operator , Type conversion.


7 Hours


Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
2



UNIT
-
7
:
INHERITANCE: Introduction, Defining derived classes, Single inheritance, Making
a private member Inheritable, Multilevel inheritance, Mult
iple inheritance, Hierarchical
inheritance, Hybrid inheritance, Virtual base classes, Abstract classes, Constructors &
Destructors in base & derived classes.






6 Hours


UNIT
-
8
:
POINTER, VIRTUAL FUNCTIONS AND POLYMORPHISM: Introduction,
Pointers, Poin
ters to Objects, this pointer, Pointers to derived classes, type
-
checking pointers,
pointers to members, Virtual functions, Pure virtual functions.

MANAGING CONSOLE I/O AND FILE I/O: C++ streams, C++ stream classes, examples of
formatted and unformatted I
/O operations, Classes for file stream operations, Methods of
Opening and Closing a File, Examples of Opening file using constructor open(), file modes
(simple programming exercises).







9 Hours



















Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
3


Table of contents

Sl. no

Contents

Page

no

1

UNIT
-
1

:PRINCIPLES OF OBJECT
-
ORIENTED
PROGRAMMING:

5 to 22


Review of
Procedure Oriented Programming


Ba
sic concepts of Object Oriented


Programming


Object, Class, Encapsulation,
Inheritance,

Polymorphis



Benefits of OOPs, Applications of OOP’s.

2

UNIT
-
2 :
THE BASIC LANGUAGE C++


A comparison of C and C++

23 to 83



Structure of C++ program with Class, Preprocessor
directives,

C++ Statements


Input/Output,


Comments, Tokens, Keywords, Identifiers,
Constants, Data types


string, pointer, reference,
boole,
enum
eration, array, complex number;


typedef names, type
compatibility, type
conversion,


C++ expressions


New and Delete.

3

UNIT
-
3 :
FUNCTIONS IN C++: Introduction

84 to 130


The main
() function, Function prototype



Call by

reference, Return by reference



Inli
ne functions, Default arguments



const A
rguments, Function Overloading,


Friend and Virtual functions, pointer to functions.

4

UNIT
-
4 :
CLAS
SES AND OBJECTS: Introduction

131 to 155


declaration and definition of a Cl
ass, defining


member functions,


C++ program with a Class, Making an outside
function Inline, Nesting of member
functions


Arrays within a class, Static data me
mbers, static
member functions


Objects


global & local objects, scope & lifetime,

memory allocation for objects,


dynamically allo
cated objects, pointers to objects,
arrays of objects, f
unction arguments with objects,


returning objects; const member functions.

5

UNIT
-
5 :
CONSTRUCTORS AND DESTRUCTORS:


Introduction, Constructors

156 to 190



Parameterized Constructors



Multiple constructors in a class



Cons
tructors with default arguments



Dynamic initialization of objects



Copy constructor

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
4




Constructing two
-
di
mensional arrays, const

6

UNIT
-
6 :
OPERATOR OVERLOADING AND TYPE
CONVERSION:


Introduction,

191 to 214


Defining operator overloadi
ng, Overloading unary


operators



Overloading binary operators, Overloading binary


operators using Friends



Rules for overloading operators, overloading a


comma operator, ov
erloading the output operator ,


Type
conversion.

7

UNIT
-
7 :
INHERITANCE: Introduction


Defining derived classes,

215 to 236


Single inheritance, Making a private member
Inheritable, Multilevel inheritance, Multiple
inheritance, Hierarchical inheritance, Hybrid
inheritance



Virtual base classes
, Abstract classes,
Constructors & Destructors in base & derived
classes.

8

UNIT
-
8 :
POINTER, VIRTUAL FUNCTIONS
AND
POLYMORPHISM: Introduction,

237 to 256


Pointers, Poi
nters to Objects, this pointer,


Pointers to derived classes


type
-
checking pointers



pointers to members



Virtual functions, Pure virtual functions.

MANAGING CONSOL
E I/O AND FILE I/O: C++
streams


C++ stream classes, examples of formatted
and
unformatted I/O operations


Classes for file stream operations



Methods of Opening and Closing a Fi
le,


using constructor open(), file modes (simple
programming exercises).







Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
5





Chapter 1

Principles of object oriented programming



review of procedure oriented programming


basic concepts of object oriented programming


objects, classes,
encapsulation, inheritance, polymorphism


Benefits of OOPs


Application of OOPs





















Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
6



"Object
-
oriented programming language" redirects here. For a list of object
-
oriented
programming languages, see

List of object
-
oriented programming languages
.

Object
-
oriented programming

(
OOP
) is a

programming paradigm

that represents concepts as
"
objects
" that have

data fields
(attributes that describe the object) and associated procedures
known as

met
hods
. Objects, which are

instances

of

classes
, are
used to interact with one
another to design applications and computer programs

An object
-
oriented program may be viewed as a collection of interacting

objects
, as opposed to
the conventional model, in which a program is seen as a list of tasks (
subroutines
) to perform.
In OOP, each object is capable of receiving messages, processing data, and sending messages
to other objects. Each object can be viewed as an independent "machine" with a d
istinct role or
responsibility. The actions (or "
methods
") on these objects are closely associated with the
object. For example, OOP

data structures

tend to "carry their own operators around with them"
(or at least "
inherit
" them from a similar object or class)
-

except when they have to be
serialized.

Simple, non
-
OOP programs may be one "long" list of statements (or commands). More
complex programs will often group smaller sections of these statements

into

functions

or

subroutines

each of which might perform a particular task. With designs o
f
this sort, it is common for some of the program's data to be 'global', i.e. accessible from any
part of the program. As programs grow in size, allowing any function to modify any piece of
data means that bugs can have wide
-
reaching effects.

In contrast,
the object
-
oriented approach encourages the programmer to place data where it is
not directly accessible by the rest of the program. Instead, the data is accessed by calling
specially written functions, commonly called

methods
, which are either bundled in with the
data or inherited from "class objects." These act as the intermediaries for retrieving or
modifying the data they control. The programming construc
t that combines data with a set of
methods for accessing and managing those data is called an object. The practice of using
subroutines to examine or modify certain kinds of data was also used in non
-
OOP

modular
programming
, well before the widespread use of object
-
oriented programming.

An object
-
oriented program will usually contain different types of objects, each type
corresponding to a particular kind of complex data

to be managed or perhaps to a real
-
world
object or concept such as a bank account, a hockey player, or a bulldozer. A program might
Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
7


well contain multiple copies of each type of object, one for each of the real
-
world objects the
program is dealing with. Fo
r instance, there could be one bank account object for each real
-
world account at a particular bank. Each copy of the bank account object would be alike in the
methods it offers for manipulating or reading its data., but the data inside each object would
d
iffer reflecting the different history of each account.

Objects can be thought of as wrapping their data within a set of functions designed to ensure
that the data are used appropriately, and to assist in that use. The object's methods will
typically inclu
de checks and safeguards that are specific to the types of data the object
contains. An object can also offer simple
-
to
-
use, standardized methods for performing
particular operations on its data, while concealing the specifics of how those tasks are
accomp
lished. In this way alterations can be made to the internal structure or methods of an
object without requiring that the rest of the program be modified. This approach can also be
used to offer standardized methods across different types of objects. As an
example, several
different types of objects might offer print methods. Each type of object might implement that
print method in a different way, reflecting the different kinds of data each contains, but all the
different print methods might be called in th
e same standardized manner from elsewhere in the
program. These features become especially useful when more than one programmer is
contributing code to a project or when the goal is to reuse code between projects.

Object
-
oriented programming has roots that

can be traced to the 1960s. As hardware and
software became increasingly complex, manageability often became a concern. Researchers
studied ways to maintain software quality and developed object
-
oriented programming in part
to address common problems by s
trongly emphasizing discrete, reusable units of programming
logic. The technology focuses on data rather than processes, with programs composed of self
-
sufficient modules ("classes"), each instance of which ("objects") contains all the information
needed t
o manipulate its own data structure ("members"). This is in contrast to the
existing

modular programming

that had been dominant for many years that focused on
the

funct
ion

of a module, rather than specifically the data, but equally provided for

code reuse
,
and self
-
sufficient reusable units of programming logic, enabling

collaboration

through the use
of linked modules (
subroutines
).

A survey by Deborah J. Armstrong of nearly 40 yea
rs of computing literature identified a
number of fundamental concepts, found in the strong majority of definitions of OOP.
[15]

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
8


Not all of these concep
ts are to be found in all object
-
oriented programming languages. For
example, object
-
oriented programming that uses classes is sometimes called

class
-
based
prog
ramming
, while

prototype
-
based programming

does not typically use classes. As a result, a
significantly different yet analogous terminology is used to d
efine the concepts
of

object

and
instance
.

Benjamin C. Pierce and some other researchers view as futile any attempt to distill OOP to a
minimal set of features. He nonetheless identifies fundamental features that support the OOP
programming style in most ob
ject
-
oriented languages:
[16]


Dynamic dispatch



when a method is invoked on an object
, the object itself determines
what code gets executed by looking up the method at run time in a table associated with the
object. This feature distinguishes an object from an

abstract data type

(or module), which
has a fixed (static) implementation of the operations for all instances. It is a programming
methodology that gives modular component development while at the same time being
very efficient.


Encapsulation

(or

multi
-
methods
, in which case the state is kept
separate)


Subtype polymorphism


Object

inheritance

(or

delegation
)


Open recursion



a special variable (syntac
tically it may be a keyword), usually
called

this

or

self, that allows a method body to invoke another method body of the same
object. This variable is

late
-
bound
; it allows a method

defined in one class to invoke
another method that is defined later, in some subclass thereof.

Similarly, in his 2003 book,

Concepts in programming languages
, John C. Mitchell identifies
four main features: dynamic dispatch,

abstraction
, subtype polymorphism, and inheritance.


Michael Lee Scott in

Programming Language Pragmatics

considers only encapsulation,
inheritance and dynamic dispatch.


Addit
ional concepts used in object
-
oriented programming include:


Classes

of objects


Instances

of classes


Methods

which act on the attached objects.


Message passing


Abstraction

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
9





A Look at Procedure Oriented Programming.

Conventional programming, using high level languages such as

COBOL,FORTRAN and C,is
commonly known as

procedure oriented programming

(POP). In the POP approach, the
problem is viewed as a sequence of things to be done such as reading,calculating and printing.
A number of functions are written to accomplish these ta
sks. The primary focus is on
functions. A typical structure for procedural programming is shown in the fig 1.1. The
technique of hierarchical decomposition has been used to specify the tasks to be completed for
solving a problem.



Procedure Oriented prog
ramming basically consists of writing a list of instructions (or actions)
for the computer to follow, and organizing these instructions into groups known as functions.
While concentrating on the development of functions, very little attention is given to t
he data
that are being used by various functions. What happens to the data? How are they affected by
the functions that work on them?


DRAWBACKS
:







In a multi
-
function program, many important data items are placed as
global

so that they may
be accessed

by all the functions.


Each function may have its own

local

data. Global data are
more vulnerable to an inadvertent change by a function. In a large program it is very difficult
to identify what data is to be used by which function. In case we need to rev
ise an external data
Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
10


structure, we also need to revise all functions that access the data. This provides an opportunity
for bugs to creep in.



Another serious drawback is that it

does not model real world problems very well.

This is because
functions are
action oriented and do not really correspond to elements of the problem.


Some characteristics exhibited by procedure
-
oriented programming are:

1)





Emphasis is on doing things (algorithms).

2)





Large programs are divided into smaller programs known a
s functions.

3)





Most of the functions share global data.

4)





Data move openly around system from function to function.

5)





Functions transform data from one form to another.

6)






Employs top
-
down approach in program design.






Object
-

Oriented Programming Paradigm

The major motivating factor in the invention of object
-

oriented approach is to remove some of
the flaws encountered in the procedural approach. OOP treats data as a critical element in the
program development and does not all
ow it to flow freely around the system. It ties data more
closely to the functions that operate on it, and protects it from accidental modification from
outside functions. OOP allows decomposition of a problem into a number of entities called
objects and t
hen builds data and functions around these objects. The data of an object can only
be accessed by the functions associated with that object. However functions of one object can
access the functions of other objects.




Some of the striking features of obj
ect


oriented programming are:


Emphasis is on data rather than procedure.


Programs are divided into what are known as objects.

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
11



Data structures are designed such that they characterize the objects.


Functions that operate on the data of an object are tied
together in the data structure.


Data is hidden and cannot be accessed by functions.


Objects may communicate with each other through functions.



New data and functions can be easily added whenever necessary.



Follows bottom
-
up approach in program design.


O
bject oriented programming as an approach that provides a way of modularizing programs by
creating partitioned memory area for both data and functions that can be used as templates for
creating copies of such modules on demand.


Thus an object is considere
d to be a partitioned area of computer memory that stores data and
set of operations that can access that data. Since memory partitions are independent, the objects
can be used in a variety of different programs without modifications.


Basic Concepts of Ob
ject


Oriented Programming

It is necessary to understand some of the concepts used extensively in object


oriented
programming. These include:


Objects


Classes


Data abstraction and encapsulation


Inheritance


Polymorphism


Dynamic binding



Message passing


For example, you might have a program that defines three different types of stacks. One stack
is used for integer values, one for character values, and one for floating
-
point values. Because
of polymorphism, you can define one set of names, push( ) and pop
( ), that can be used for all
three stacks. In your program you will create three specific versions of these functions, one for
each type of stack, but names of the functions will be the same. The compiler will
Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
12


automatically select the right function based

upon the data being stored. Thus, the interface to a
stack

the functions push( ) and pop( )

are the same no matter which type of stack is being

used. The individual versions of these functions define the specific implementations (methods)
for each type of

data. Polymorphism helps reduce complexity by allowing the same interface to
be used to access a general class of actions. It is the compiler's job to select the specific action
(i.e., method) as it applies to each situation. You, the programmer, don't ne
ed to do this
selection manually. You need only remember and utilize the general interface. The first
objectoriented programming languages were interpreters, so polymorphism was, of course,
supported at run time. However, C++ is a compiled language. Theref
ore, in C++, both run
-
time
and compile
-
time polymorphism are supported.


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 t
he 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 each other. For
example, If “customer” and “acc
ount” are two objects in a program, then the customer object
may send a message to account object requesting for the bank balance. Each object contains
data and code to manipulate the data. Objects can interact without having to know each others
data or co
de. It is sufficient to know the type of messages accepted, and the type of response
returned by the objects.

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
13



Classes

We just mentioned that objects can contain data, and code to manipulate that data. The entire
set of data and code of an object can be m
ade a user


defined data type with the help of a
class. Infact objects are variables of the type class. Once a class has been defined, we can
create any number of objects belonging to that class. Each object is associated with the data of
type class with
which they are created. A class is thus a collection of objects similar type. For
example mango,apple, and orange are members of the class fruit. Classes are user defined data
types and behave like the built in types of a programming language. The syntax u
sed is no
different than the syntax used to create an integer object in C. If fruit has been defined as a
class, then the statement

fruit mango;

will create an object mango belonging to the class fruit.


This is similar to the statement used in C:

int a;


Data Abstraction and Encapsulation

The wrapping up of data and functions into a single unit (called class) is known as
encapsulation.

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.

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
14


Abstra
ction

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

functions

to oper
ate 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

meth
ods

or

member

functions.

Since the classes use the concept of data abstraction, they are known as Abstract Data types
(ADT).


Inheritance

Inheritance is the process by which objects of one class acquire the properties of objects of
another class. It
supports the concept of
hierarchial classification.

For example, the bird ‘robin’
is a part of the class ‘flying bird’ which is again a part of the class ‘bird’. The principle behind
this sort of division is that each derived class shares common characteris
tics with the class
from which it is derived as illustrated in fig 1.4.


Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
15


In OOP, the concept of inheritance provides the idea of

reusability.

This means that we can add
additional features to an existing class without modifying it. This is possible by der
iving a new
class from the existing one. The new class will have the combined features of both the classes.
The real appeal and power of the inheritance mechanism is that it allows the programmer to
reuse a class that is almost, but not exactly, what he wa
nts, and to tailor the class in such a way
that it does not introduce any undesirable side
-
effects into the rest of the classes.

Note that each sub
-
class defines only those features that are unique to it. Without the use of
classification, each class would

explicitly include all its features.



























































Polymorphism

Polymorphism is another important OOP concept. Polymorphism, a greek term means 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 operatio
n would produce a third string by concatenation. The
process of making an operator to exhibit different behaviors in different instances is known
a

operator overloading.


Fig 1.5 illustrates that a single function name can be used to handle different numbe
r 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 p
lays an important role in allowing objects having different internal structures
to share the same external interface. This means that a general class of operations may be
accessed in the same manner even though specific actions associated with each operati
on may
differ. Polymorphism is extensively used in implementing inheritance.

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
16





Dynamic Binding

Binding refers to the linking of a procedure call to the code to be executed in response to the
call. Dynamic binding (also known as late binding) means that t
he code associated with a given
procedure call is not known until the time of the call at rub
-
time. It is associated with
polymorphism and inheritance. A function call associated with a polymorphic reference
depends on the dynamic type of that reference.

C
onsider the procedure “draw” in fig 1.5. By inheritance, every object will have this
procedure. Its algorithm is, however, unique to each object and so the draw procedure will be
redefined in each class that defines the object. At run
-
time, the code matchi
ng the object under
current reference will be called.


Message passing

An object
-

oriented program consists of a set of objects that communicate with each other. The
process of programming in an object
-
oriented language,therefore involves the following bas
ic
steps:

1.






Creating classes that define objects and their behavior,

2.






Creating objects from class definitions, and

3.






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.

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
17


A message for an object is a request for execution of a p
rocedure, and therefore will invoke a
function (procedure) in the receiving object that generates the desired result. Message passing
involves specifying the name of the function (message) and the information to be sent.

Example:












Benefits of OO
Ps


Through inheritance, we can eliminate redundant code and extend the use of exiting
classes.


We can build programs from the standard working modules that communicate with one
another,rather than having to start writing the code from scratch. This leads t
o saving of
development time and higher productivity.


The principle of data hiding helps the programmer to build secure programs that cannot be
invaded by code in other parts of the program.


It is possible to have multiple instances of an object to co
-
exis
t without any interference.


It is possible to map objects in the problem domain to those in the program.


It is easy to partition the work in a project based on objects.


It is easy to partition the work in a project based on objects.


The data
-
centered desig
n approach enables us to capture more details of a model on
implementable form.


Object oriented systems can be easily upgraded from small to large systems.


Message passing techniques for communication between objects makes the interface
descriptions with e
xternal systems much simpler.


Software complexity can be easily managed.


A Sample C++ Program


Let's start with the short sample C++ program shown here.

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
18


#include <iostream>

using namespace std;

int main()

{

int i;

cout << "This is output.
\
n"; // this is a

single line comment

/* you can still use C style comments */

// input a number using >>

cout << "Enter a number: ";

cin >> i;

// now, output a number using <<

cout << i << " squared is " << i*i << "
\
n";

return 0;





Increment and Decrement

C/C++ includes

two useful operators not found in some other computer languages. These are

the increment and decrement operators, ++ and −−. The operator ++ adds 1 to its operand,

and
−−subtracts 1.

In other words:

x = x+1;

is the same as

++x;

and

x = x
-
1;

is the same as

x
--
;

Both the increment and decrement operators may either precede (prefix) or follow (postfix) the

operand.

For example, x = x+1; can be written

++x;

or

x++;

There is, however, a difference between the prefix and postfix forms when you use these

operator
s in an expression. When an increment or decrement operator precedes its operand, the

increment or decrement operation is performed before obtaining the value of the operand for

use in the expression. If the operator follows its operand, the value of the o
perand is obtained

before incrementing or

decrementing it.



For instance,

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
19


x = 10;

y = ++x;

sets y to 11. However, if you write the code as

x = 10;

y = x++;

y is set to 10. Either way, x is set to 11; the difference is in when it happens. Most C/C++

compil
ers produce very fast, efficient object code for increment and decrement operations


code that is better than that generated by using the equivalent assignment statement. For this

reason, you should use the increment and decrement operators when you can.

H
ere is the precedence of the arithmetic operators:

highest ++







(unary minus)

lowest +


Operators on the same level of precedence are evaluated by the compiler from left to right. Of

course, you can use parentheses to alter the order of evaluation.
C/C++ treats parentheses in the

same way as virtually all other computer languages. Parentheses force an operation, or set of

operations, to have a higher level of precedence.

The following program contains the function xor( ), which returns the outcome of

an exclusive
OR operation performed on its two arguments:

#include <stdio.h>

int xor(int a, int b);

int main(void)

{

printf("%d", xor(1, 0));

printf("%d", xor(1, 1));

printf("%d", xor(0, 1));

printf("%d", xor(0, 0));

return 0;


}





Applications


The promising areas for application of OOP include:


Real
-
time systems

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
20



Simulation and modeling


Object oriented databases


Hypertext, hypermedia and expertext


AI and expert systems


Neural networks and parallel progr
amming


Decision support and office automation systems


CIM/CAM/CAD systems.



Example programs

1.

/* Divide the first number by the second. */

#include <stdio.h>

int main(void)

{

int a, b;

printf("Enter two numbers: ");

scanf("%d%d", &a, &b);

if(b)
printf("%d
\
n", a/b);

else printf("Cannot divide by zero.
\
n");

return 0;

}



2.

/* Count spaces */

#include <stdio.h>

int main(void)

{

char s[80], *str;

int space;

printf("Enter a string: ");

gets(s);

str = s;

for(space=0; *str; str++) {

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
21


if(*str != ' ') contin
ue;

space++;

}

printf("%d spaces
\
n", space);

return 0;

}

3.

loads a two
-
dimensional array with the numbers 1 through 12 and

prints them row by row.

#include <stdio.h>

int main(void)

{

int t, i, num[3][4];

for(t=0; t<3; ++t)

for(i=0; i<4; ++i)

num[t][i] =
(t*4)+i+1;

/* now print them out */

for(t=0; t<3; ++t) {

for(i=0; i<4; ++i)

printf("%3d ", num[t][i]);

printf("
\
n");

}

return 0;

}

4.

/* A very simple text editor. */

#include <stdio.h>

#define MAX 100

#define LEN 80

char text[MAX][LEN];

int main(void)

{

register int t, i, j;

printf("Enter an empty line to quit.
\
n");

for(t=0; t<MAX; t++) {

printf("%d: ", t);

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
22


gets(text[t]);

if(!*text[t]) break; /* quit on blank line */

}

for(i=0; i<t; i++) {

for(j=0; text[i][j]; j++) putchar(text[i][j]);

Object Oriented Pro
gramming with C++ 10CS36

Dept. of CSE, SJBIT 33

putchar('
\
n');

}

return 0;

}

5.

Square and square root of a number

#include <stdio.h>

int sqr(int x);

int main(void)

{

int t=10;

printf("%d %d", sqr(t), t);

return 0;

}

int sqr(int x)

{

x = x*x;

return(x);

}







Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
23















Unit
-
2

The basic language C++


A
comparison

with C


Structure of C++


Program with class


Pre
-
processor directives


C++ statements


I/O, comments, tokens, keywords, constants,


Data types


Strings, pointers, reference


Enumeration, array, complex
numbers


Typedef names, type compatability, conversion


Operators in c++

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
24



Precedence, overloading


New and delete












Procedure Oriented vs Object Oriented Programming

Programming, at a high level, is the process of solving a problem in an abstract
fashion, then
writing that solution out in code. Object Orientated Programming and Procedure Oriented
Programming are basically two different paradigms for writing code; more fundamentally, they
are two different ways of thinking about and modeling the pro
blem's solution. In a nutshell,
Object Oriented programming deals with the elemental basic parts or building blocks of the
problem, whereas Procedural programming focuses on the steps required to produce the
desired outcome.

Object Orientation [OO], in gen
eral, is a methodology for modeling the real world or at
least the problem being solved, by decomposing the problem into smaller discrete pieces called
"Objects". What makes an "object" unique is the formal and explicit combination these smaller
pieces' be
havior with its' data into a single entity. The object's behaviors are called methods in
OO terminology, while its data is called the Object's state. "Objects" will make up every part of
the solution, that is, every part of the program will be made from ob
jects. Formally, there are
technical attributes of that must be present for a program (or a programming Language) to be
considered Object Oriented, such as inheritance, polymorphism, encapsulation, and protection;
Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
25


aspects of these terms are still under deb
ate in many programming circles, so no, 100% certain,
absolutely clear definition is possible. The core concept, though, is that an "Object" is binding
together of data and behavior, and Object Oriented programming, is the use of Objects while
solving the
problem.


People regularly interact with real objects, such as a book, or a pencil in the real world, Object
Oriented programming provides tools to deal with these objects, such as "a book," in the
abstract world of writing software more logically and natu
rally.



Procedural Programming, by contrast, is a methodology for modeling the real world or the
problem being solved, by determining the steps and the order of those steps that must be
followed in order to reach a desired outcome or specific program stat
e. For example, consider
the problem: "calculate the month end closing balance for an account." The process is take the
starting balance, subtract all the debits and add all the credits for the period and then you arrive
closing balance. The key point for
procedural programming is identification and articulation of
the process or steps that must be followed.

In addition to programming, programming languages can also be considered Object Oriented
[OO] or Procedural. The language used for writing code does no
t determine if a program is
Object Oriented or Procedural; Object Orientation and Procedural, is a way of solving the
problem or a way of thinking about the problem, not the language used to write the code. It is
possible to write Object Oriented Programs
in C, a procedural language, and similarly, you can
write a Procedural Program in Java, an OO language. Object Oriented Languages have the
benefit of supporting key aspect of Object Orientation in the language itself, making it easier to
implement Object O
riented programs, and providing the native language support object
oriented aspects like polymorphism or inheritance.


Software tries to model the real world in some way: Object Oriented Programming, boils down
to what object do I have and how do they rela
te to and interact with each other. Procedural
programming, boils down to what steps do I need to take to get the program in a certain state.


Procedure Oriented Programming

1.Prime focus is on functions and procedures that operate on data

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
26


2.Large programs

are divided into smaller program units called functions

3.Data and the functions that act upo it are treated as separate entities.

4.Data move freely around the systems from one function to another.

5.Program design follows “Top Down Approach”.


Object Or
iented Programming

1.Here more emphasis is laid on the data that is being operated and not the functions or
procedures

2.Programs are divided into what are called objects.

3.Both data and functions are treated together as an integral entity.

4.Data is hidd
en and cannot be accessed by external functions.

5.Program design follows “Bottom UP Approach”.





Preprocessor directives

Preprocessor directives are lines included in the code of our programs that are not program
statements but directives for the
preprocessor. These lines are always preceded by a hash sign
(
#
). The preprocessor is executed before the actual compilation of code begins, therefore the
preprocessor digests all these directives before any code is generated by the statements.


These
preprocessor directives extend only across a single line of code. As soon as a newline
character is found, the preprocessor directive is considered to end. No semicolon (;) is expected
at the end of a preprocessor directive. The only way a preprocessor dir
ective can extend
through more than one line is by preceding the newline character at the end of the line by a
backslash (
\
).


macro definitions

(#define, #undef)

To define preprocessor macros we can use

#define
. Its format is:


#define identifier replacem
ent


Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
27


When the preprocessor encounters this directive, it replaces any occurrence of

identifier

in the
rest of the code by

replacement
. This

replacement

can be an expression, a statement, a block or
simply anything. The preprocessor does not understand C++,

it simply replaces any occurrence
of

identifier

by

replacement
.

#define TABLE_SIZE 100

int

table1[TABLE_SIZE];

int

table2[TABLE_SIZE];

After the preprocessor has replaced

TABLE_SIZE
, the code becomes equivalent to:

int

table1[100];

int

table2[100];

This
use of #define as constant definer is already known by us from previous tutorials,
but

#define

can work also with parameters to define function macros:

#define getmax(a,b) a>b?a:b

This would replace any occurrence of

getmax

followed by two arguments by the replacement
expression, but also replacing each argument by its identifier, exactly as you would expect if it
was a function:

// function macro

#include <iostream>

using

namespace

std;


#define getmax(a,b) ((a)>(b)?(a):(b))


int

main()

{


int

x=5, y;


y= getmax(x,2);


cout << y << endl;


cout << getmax(7,x) << endl;


return

0;

}


Defined macros are not affected by block structure. A macro lasts until it is undefined with the
Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
28


#undef preprocessor directive:

#define TABLE_
SIZE 100

int

table1[TABLE_SIZE];

#undef TABLE_SIZE

#define TABLE_SIZE 200

int

table2[TABLE_SIZE];


This would generate the same code as:

int

table1[100];

int

table2[200];

Function macro definitions accept two special operators (
#

and

##
) in the replacement

sequence:If the operator

#

is used before a parameter is used in the replacement sequence, that
parameter is replaced by a string literal (as if it were enclosed between double quotes)

#define str(x) #x

cout << str(test);

This would be translated into:

co
ut <<
"test"
;

The operator

##

concatenates two arguments leaving no blank spaces between them:

#define glue(a,b) a ## b

glue(c,out) <<
"test"
;

This would also be translated into:

cout <<
"test"
;

Because preprocessor replacements happen before any C++
syntax check, macro definitions
can be a tricky feature, but be careful: code that relies heavily on complicated macros may
seem obscure to other programmers, since the syntax they expect is on many occasions
different from the regular expressions programm
ers expect in C++.


Conditional inclusions (#ifdef, #ifndef, #if, #endif, #else and #elif)


These directives allow to include or discard part of the code of a program if a certain condition
Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
29


is met.


#ifdef

allows a section of a program to be compiled only
if the macro that is specified as the
parameter has been defined, no matter which its value is. For example:


#ifdef TABLE_SIZE

int

table[TABLE_SIZE];

#endif

In this case, the line of code

int table[TABLE_SIZE];

is only compiled if

TABLE_SIZE

was
previously defined with
#define
, independently of its value. If it was not defined, that line will
not be included in the program compilation.


#ifndef

serves for the exact opposite: the code between

#ifndef

and

#endif

directives is only
compiled if the
specified identifier has not been previously defined. For example:

#ifndef TABLE_SIZE

#define TABLE_SIZE 100

#endif

int

table[TABLE_SIZE];

In this case, if when arriving at this piece of code, the

TABLE_SIZE

macro has not been
defined yet, it would be
defined to a value of 100. If it already existed it would keep its
previous value since the

#define

directive would not be executed.


The

#if
,

#else

and

#elif

(i.e., "else if") directives serve to specify some condition to be met in
order for the portion o
f code they surround to be compiled. The condition that
follows

#if

or

#elif

can only evaluate constant expressions, including macro expressions. For
example:


#if TABLE_SIZE>200

#undef TABLE_SIZE

#define TABLE_SIZE 200



#elif TABLE_SIZE<50

#undef
TABLE_SIZE

#define TABLE_SIZE 50



Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
30


#else

#undef TABLE_SIZE

#define TABLE_SIZE 100

#endif



int

table[TABLE_SIZE];

Notice how the whole structure of

#if
,

#elif

and

#else

chained directives ends with

#endif
.


The behavior of

#ifdef

and

#ifndef

can also be
achieved by using the special
operators

defined

and

!defined
respectively in any

#if

or

#elif

directive:

#if !defined TABLE_SIZE

#define TABLE_SIZE 100

#elif defined ARRAY_SIZE

#define TABLE_SIZE ARRAY_SIZE

int

table[TABLE_SIZE];

#endif

Line control (#line)

When we compile a program and some error happens during the compiling process, the
compiler shows an error message with references to the name of the file where the error
happened and a line number, so it is easier to find the code generating the error.


The

#line

directive allows us to control both things, the line numbers within the code files as
well as the file name that we want that appears when an error takes place. Its format is:



#line number "filename"


Where

number

is the new line number that
will be assigned to the next code line. The line
numbers of successive lines will be increased one by one from this point on.


"filename"

is an optional parameter that allows to redefine the file name that will be shown.
For example:


#line 20 "assigning v
ariable"

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
31


int

a?;

This code will generate an error that will be shown as error in file

"assigning variable"
, line 20.


Error directive (#error)

This directive aborts the compilation process when it is found, generating a compilation the
error that can be
specified as its parameter:

#ifndef __cplusplus

#error A C++ compiler is required!

#endif

This example aborts the compilation process if the macro name

__cplusplus

is not defined (this
macro name is defined by default in all C++ compilers).



Source file
inclusion (#include)

This directive has also been used assiduously in other sections of this tutorial. When the
preprocessor finds an
#include

directive it replaces it by the entire content of the specified file.
There are two ways to specify a file to be i
ncluded:


#include "file"

The only difference between both expressions is the places (directories) where the compiler is
going to look for the file. In the first case where the file name is specified between double
-
quotes, the file is searched first in the

same directory that includes the file containing the
directive. In case that it is not there, the compiler searches the file in the default directories
where it is configured to look for the standard header files.

If the file name is enclosed between angl
e
-
brackets

<>

the file is searched directly where the
compiler is configured to look for the standard header files. Therefore, standard header files are
usually included in angle
-
brackets, while other specific header files are included using quotes.



Prag
ma directive (#pragma)

This directive is used to specify diverse options to the compiler. These options are specific for
the platform and the compiler you use. Consult the manual or the reference of your compiler
Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
32


for more information on the possible parame
ters that you can define with

#pragma
.


If the compiler does not support a specific argument for

#pragma
, it is ignored
-

no error is
generated.


Predefined macro names

The following macro names are defined at any time:


macro

value

__LINE__

Integer value

representing the current line in the source code file being compiled.

__FILE__

A string literal containing the presumed name of the source file being compiled.

__DATE__

A string literal in the form "Mmm dd yyyy" containing the date in which the
compilation process began.

__TIME__

A string literal in the form "hh:mm:ss" containing the time at which the
compilation process began.

__cplusplus

An integer value. All C++ compilers have this constant defined to some value. If
the compiler is fully com
pliant with the C++ standard its value is equal or greater
than 199711L depending on the version of the standard they comply.


For example:

// standard macro names

#include <iostream>

using

namespace

std;


int

main()

{


cout <<
"This is the line number "

<< __LINE__;


cout <<
" of file "

<< __FILE__ <<
".
\
n"
;


cout <<
"Its compilation began "

<< __DATE__;

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
33



cout <<
" at "

<< __TIME__ <<
".
\
n"
;


cout <<
"The compiler gives a __cplusplus value of "

<< __cplusplus;


return

0;

}

Ans:
This is the line
number 7 of file /home/jay/stdmacronames.cpp.

Its compilation began Nov 1 2005 at 10:12:29.

The compiler gives a __cplusplus va

lue of 1


Variables. Data Types.

The usefulness of the

"Hello World"

programs shown in the previous section is quite
questionable. We had to write several lines of code, compile them, and then execute the
resulting program just to obtain a simple sentence written on the screen as result. It certainly
would have been much fa
ster to type the output sentence by ourselves. However, programming
is not limited only to printing simple texts on the screen. In order to go a little further on and to
become able to write programs that perform useful tasks that really save us work we ne
ed to
introduce the concept of

variable
.


Let us think that I ask you to retain the number 5 in your mental memory, and then I ask you to
memorize also the number 2 at the same time. You have just stored two different values in
your memory. Now, if I ask y
ou to add 1 to the first number I said, you should be retaining the
numbers 6 (that is 5+1) and 2 in your memory. Values that we could now
-
for example
-

subtract and obtain 4 as result.


The whole process that you have just done with your mental memory is
a simile of what a
computer can do with two variables. The same process can be expressed in C++ with the
following instruction set:


a = 5;

b = 2;

a = a + 1;

result = a
-

b



Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
34


Obviously, this is a very simple example since we have only used two small intege
r values, but
consider that your computer can store millions of numbers like these at the same time and
conduct sophisticated mathematical operations with them.


Therefore, we can define a

variable

as a portion of memory to store a determined value.


Each
variable needs an identifier that distinguishes it from the others. For example, in the
previous code the
variable identifiers

were

a
,

b

and

result
, but we could have called the
variables any names we wanted to invent, as long as they were valid
identifiers.



Identifiers

A

valid identifier

is a sequence of one or more letters, digits or underscore characters (
_
).
Neither spaces nor punctuation marks or symbols can be part of an identifier. Only letters,
digits and single underscore characters are

valid. In addition, variable identifiers always have
to begin with a letter. They can also begin with an underline character (
_

), but in some cases
these may be reserved for compiler specific keywords or external identifiers, as well as
identifiers conta
ining two successive underscore characters anywhere. In no case can they
begin with a digit.


Another rule that you have to consider when inventing your own identifiers is that they cannot
match any keyword of the C++ language nor your compiler's specific
ones, which are

reserved
keywords
. The standard reserved keywords are:


asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do,
double, dynamic_cast, else, enum, explicit, export, extern, false, float, for,
friend, goto, if,
inline, int, long, mutable, namespace, new, operator, private, protected, public, register,
reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this,
throw, true, try, typedef, typeid, typename,

union, unsigned, using, virtual, void, volatile,
wchar_t, while



Additionally, alternative representations for some operators cannot be used as identifiers since
they are reserved words under some circumstances:


Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
35



and, and_eq, bitand, bitor, compl, not,
not_eq, or, or_eq, xor, xor_eq



Your compiler may also include some additional specific reserved keywords.


Very important:

The C++ language is a

"case sensitive"

language. That means that an
identifier written in capital letters is not equivalent to anot
her one with the same name but
written in small letters. Thus, for example, the
RESULT

variable is not the same as
the

result

variable or the

Result

variable. These are three different variable identifiers.



Fundamental data types

When programming, we
store the variables in our computer's memory, but the computer has to
know what kind of data we want to store in them, since it is not going to occupy the same
amount of memory to store a simple number than to store a single letter or a large number, and
t
hey are not going to be interpreted the same way.


The memory in our computers is organized in bytes. A byte is the minimum amount of
memory that we can manage in C++. A byte can store a relatively small amount of data: one
single character or a small inte
ger (generally an integer between 0 and 255). In addition, the
computer can manipulate more complex data types that come from grouping several bytes,
such as long numbers or non
-
integer numbers.


Next you have a summary of the basic fundamental data types
in C++, as well as the range of
values that can be represented with each one:


Name

Description

Size*

Range*

char

Character or small integer.

1byte

signed:
-
128 to 127

unsigned: 0 to 255

short
Short Integer.

2bytes

signed:
-
32768 to 32767

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
36


int
(
short
)

unsigned: 0 to 65535

int

Integer.

4bytes

signed:
-
2147483648 to
2147483647

unsigned: 0 to 4294967295

long
int

(
long
)

Long integer.

4bytes

signed:
-
2147483648 to
2147483647

unsigned: 0 to 4294967295

bool

Boolean value. It can take one of two
values: true

or false.

1byte

true

or

false

float

Floating point number.

4bytes

+/
-

3.4e +/
-

38 (~7 digits)

double

Double precision floating point number.

8bytes

+/
-

1.7e +/
-

308 (~15 digits)

long double

Long double precision floating point
number.

8bytes

+/
-

1.7e
+/
-

308 (~15 digits)

wchar_t

Wide character.

2

or

4
bytes

1 wide character


* The values of the columns

Size

and

Range

depend on the system the program is compiled for.
The values shown above are those found on most 32
-
bit systems. But for other systems,

the
general specification is that

int

has the natural size suggested by the system architecture
(one

"word"
) and the four integer types

char
,

short
,

int

and
long

must each one be at least as
large as the one preceding it, with

char

being always one byte in

size. The same applies to the
floating point types

float
,

double

and

long double
, where each one must provide at least as
much precision as the preceding one.



Declaration of variables

In order to use a variable in C++, we must first declare it
specifying which data type we want it
to be. The syntax to declare a new variable is to write the specifier of the desired data type (like
Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
37


int, bool, float...) followed by a valid variable identifier. For example:

int

a;

float

mynumber;

These are two valid

declarations of variables. The first one declares a variable of type

int

with
the identifier

a
. The second one declares a variable of type

float

with the identifier

mynumber
.
Once declared, the variables

a

and
mynumber

can be used within the rest of their
scope in the
program.


If you are going to declare more than one variable of the same type, you can declare all of them
in a single statement by separating their identifiers with commas. For example:

int

a, b, c;

This declares three variables (
a
,

b

and

c
),

all of them of type

int
, and has exactly the same
meaning as:

int

a;

int

b;

int

c;

The integer data types

char
,

short
,

long

and

int

can be either signed or unsigned depending on
the range of numbers needed to be represented. Signed types can represent
both positive and
negative values, whereas unsigned types can only represent positive values (and zero). This can
be specified by using either the specifier
signed

or the specifier

unsigned

before the type name.
For example:


unsigned

short

int

NumberOfSist
ers;

signed

int

MyAccountBalance;


By default, if we do not specify either

signed

or

unsigned

most compiler settings will assume
the type to be signed, therefore instead of the second declaration above we could have written:

int

MyAccountBalance;

with
exactly the same meaning (with or without the keyword

signed
)


An exception to this general rule is the

char

type, which exists by itself and is considered a
different fundamental data type from

signed char

and

unsigned char
, thought to store
Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
38


characters.
You should use either

signed

or
unsigned

if you intend to store numerical values in
a

char
-
sized variable.


short

and

long

can be used alone as type specifiers. In this case, they refer to their respective
integer fundamental types:

short

is equivalent to

s
hort int

and

long

is equivalent to

long int
.
The following two variable declarations are equivalent:

short

Year;

short

int

Year;

Finally,

signed

and

unsigned

may also be used as standalone type specifiers, meaning the same
as

signed int

and
unsigned int

respectively. The following two declarations are equivalent:


unsigned

NextYear;

unsigned

int

NextYear;

To see what variable declarations look like in action within a program, we are going to see the
C++ code of the example about your mental memory
proposed at the beginning of this section:

// operating with variables


#include <iostream>

using

namespace

std;


int

main ()

{


// declaring variables:


int

a, b;


int

result;



// process:


a = 5;


b = 2;


a = a + 1;


result = a
-

b;



// print
out the result:


cout << result;

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
39




// terminate the program:


return

0;

}

Ans:
4

Do not worry if something else than the variable declarations themselves looks a bit strange to
you. You will see the rest in detail in coming sections.



Scope of variables

All the variables that we intend to use in a program must have been declared with its type
specifier in an earlier point in the code, like we did in the previous code at the beginning of the
body of the function main when we declared that

a
,

b
, and

result

were of type

int
.


A variable can be either of global or local scope. A global variable is a variable declared in the
main body of the source code, outside all functions, while a local variable is one declared
within the body of a function or a block.




Global variables can be referred from anywhere in the code, even inside functions, whenever it
is after its declaration.


The scope of local variables is limited to the block enclosed in braces (
{}
) where they are
Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
40


declared. For example, if they are declar
ed at the beginning of the body of a function (like in
function

main
) their scope is between its declaration point and the end of that function. In the
example above, this means that if another function existed in addition to

main
, the local
variables decl
ared in

main

could not be accessed from the other function and vice versa.



Initialization of variables

When declaring a regular local variable, its value is by default undetermined. But you may
want a variable to store a concrete value at the same moment

that it is declared. In order to do
that, you can initialize the variable. There are two ways to do this in C++:


The first one, known as

c
-
like initialization
, is done by appending an equal sign followed by
the value to which the variable will be initial
ized:


type identifier = initial_value ;


For example, if we want to declare an

int

variable called

a

initialized with a value of 0 at the
moment in which it is declared, we could write:

int

a = 0;

The other way to initialize variables, known as

constructor initialization
, is done by enclosing
the initial value between parentheses (
()
):



type identifier (initial_value) ;


For example:

int

a (0);

Both ways of initializing variables are valid and equivalent in C++.

// initialization of variables


#include <iostream>

using

namespace

std;


int

main ()

{

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
41



int

a=5;
// initial value = 5


int

b(2);
// initial value = 2


int

result;
// initial value undetermined



a = a + 3;


result = a
-

b;


cout << result;



return

0;

}

Ans:
6

Introduction to strings

Variables that can store non
-
numerical values that are longer than one single character are
known as strings.


The C++ language library provides support for strings through the standard

string

class. This is
not a

fundamental type, but it behaves in a similar way as fundamental types do in its most
basic usage.


A first difference with fundamental data types is that in order to declare and use objects
(variables) of this type we need to include an additional header

file in our source
code:

<string>

and have access to the

std

namespace (which we already had in all our previous
programs thanks to the

using namespace

statement).

// my first string

#include <iostream>

#include <string>

using

namespace

std;


int

main ()

{


string mystring =
"This is a string"
;


cout << mystring;

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
42



return

0;

}

Ans:
This is a string

As you may see in the previous example, strings can be initialized with any valid string literal
just like numerical type variables can be initialized to any
valid numerical literal. Both
initialization formats are valid with strings:

string mystring =
"This is a string"
;

string mystring (
"This is a string"
);

Strings can also perform all the other basic operations that fundamental data types can, like
being
declared without an initial value and being assigned values during execution:

// my first string

#include <iostream>

#include <string>

using

namespace

std;


int

main ()

{


string mystring;


mystring =
"This is the initial string content"
;


cout <<

mystring << endl;


mystring =
"This is a different string content"
;


cout << mystring << endl;


return

0;

}

Ans:
This is the initial string content

This is a different string content

Literals

Literals

are the most obvious kind of constants. They are
used to express particular values
within the source code of a program. We have already used these previously to give concrete
values to variables or to express messages we wanted our programs to print out, for example,
Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
43


when we wrote:

a = 5;

the

5

in this p
iece of code was a

literal constant
.


Literal constants can be divided in

Integer Numerals
,

Floating
-
Point
Numerals
,

Characters
,

Strings

and

Boolean Values
.


Integer Numerals

1776

707

-
273

They are numerical constants that identify integer decimal values.
Notice that to express a
numerical constant we do not have to write quotes (
"
) nor any special character. There is no
doubt that it is a constant: whenever we write

1776

in a program, we will be referring to the
value 1776.


In addition to decimal numbers
(those that all of us are used to using every day), C++ allows
the use of octal numbers (
base 8
) and hexadecimal numbers (
base 16
) as literal constants. If we
want to express an octal number we have to precede it with a

0

(a

zero

character). And in order
t
o express a hexadecimal number we have to precede it with the characters

0x

(
zero
,

x
). For
example, the following literal constants are all equivalent to each other:


75
// decimal

0113
// octal

0x4b
// hexadecimal


All of these
represent the same number: 75 (seventy
-
five) expressed as a base
-
10 numeral,
octal numeral and hexadecimal numeral, respectively.



Literal constants, like variables, are considered to have a specific data type. By default, integer
literals are of type
int
.

However, we can force them to either be unsigned by appending
the

u

character to it, or long by appending

l
:

75
// int

Object oriented programming using C++


10EE664


Department of EEE, SJBIT

Page
44


75u
// unsigned int

75l
// long

75ul
// unsigned long

In both cases, the suffix can be specified using eithe
r upper or lowercase letters.



Floating Point Numbers

They express numbers with decimals and/or exponents. They can include either a decimal
point, an

e

character (that expresses "by ten at the Xth height", where X is an integer value that
follows the

e

character), or both a decimal point and an