0% found this document useful (0 votes)
64 views65 pages

DR - Jyothirmayi Degree College, Adoni.: Paper-III - Object Oriented Programming Using C++: Unit-1 Fundamentals

Uploaded by

hafsaadn
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
0% found this document useful (0 votes)
64 views65 pages

DR - Jyothirmayi Degree College, Adoni.: Paper-III - Object Oriented Programming Using C++: Unit-1 Fundamentals

Uploaded by

hafsaadn
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 65

Object Oriented Programming in C++ C.Md.

Jamsheed

Dr.jyothirmayi degree college, Adoni.


III-B.Com Computers
Paper-III -Object Oriented Programming Using C++:
Unit-1 Fundamentals:
Introduction: Development in software technology continue to be dynamic. Development of
new tools and techniques has forced the software industry to continuously look for new
approaches to software design and development which is critical in view of the increasing
complexity of software systems. All these activities led to a serious crisis within the industry.
The following issues need to be resolved to overcome this crisis:
1) How to represent real-life entities of problems in the system?
2) How to design systems with open interface?
3) How to ensure reusability and extensibility of modules?
4) How to develop modules that are tolerant to any changes in future?
5) How to improve software productivity and decrease software cost?
6) How to improve the quality of software?
7) How to manage time schedules?
8) How to industrialize the software development process?
Software products should be evaluated carefully for their quality before they are
delivered and implemented. Some of the quality issues to be considered for critical evaluation:
1) Correctness 2) Maintainability 3) Security 4) Openness and interoperability 5) Portability 6)
Security 7) Integrity 8) User friendliness.
 PROGRAMMING PARADIGM’s:
As many software experts point out, the complexity of the software is an essential
property. The trend in the evolution of high-level languages and the shift of focus from
‘ Programming –in-the-small ‘ to ‘Programming-in-the-large’ has simplified the task of the
software development team. This shift in programming paradigeddc3m is categorized into the
following: 1) Monolithic programming 2) Procedural Programming 3) Structured Programming
and 4) Object Oriented Programming.
1) Monolithic programming: The programs written in these languages exhibit relatively flat
physical structure. They consist of only global data and sequential code. Program flow control is
achieved through the use of jumps and the program code is duplicated each time it is to be used.
It is suitable for developing small and simple application. There is no support for data
abstraction and it is difficult to maintain or enhance the program code. Ex: Assembly Language
and Basic.

-1-
Object Oriented Programming in C++ C.Md.Jamsheed

2) Procedural programming: it refers to conventional programming using high level


languages. It basically consists of writing a list of instruction for the computer to follow, and
organizing these instructions into groups known as functions. Programs are organized in the
form of subroutines and the 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, is very difficult to identify what data is used by which function that is it is difficult to
maintain and enhance the programs code.
Characteristics:
1) Emphasis is on algorithms.
2) Large data is divided in to smaller programs called functions
3) Most of the functions share global data.
4) Data more openly around the system from function to function.
5) Function transforms data from one form to another.

Subprograms/functions
EX: Fortran and Cobol.
3) Structured programming: It is a mechanism in which large data is handled. large
programming projects consists of large development teams, developing different, parts of the
same project independently. The usages of separately compiled modules. Programs consists of
multiple modules are in turn, each module has a set of functions of relates types.
Features:1) Emphasis on algorithm rather than date.
2) Programs are divided into individual procedures that perform different tasks.
3) Procedures are independent and have their own local data and processing logic.
4) Parameter passing facility between the procedures for information communication.
5) Support for modular programming.
6) Scope of data items is further controlled across modules.

Subprograms
Ex: Pascal, c.

-2-
Object Oriented Programming in C++ C.Md.Jamsheed

4) Object oriented programming: OOP’s treats data as a critical element in the development
and does not allow it flow freely around the program. It ties data more closely to the function
that operate on it and protects it from accidental modification from outside functions.
OOP allows us to decompose a problem into a number of entities called objects and then
builds data functions around these entities. The data of an object can be accessed only by the
functions associated with that object. Functions of one object can access the functions of other
objects.
Def: object oriented programming is 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.

 FEATURES OF OOP:
1) Emphasis is on data rather than procedures.
2) Programs are divided into objects.
3) Data structures are designed such that they characterize the objects.
4) Functions that operate on the data of an object are tied together in the data structures.
5) Data is hidden and cannot be accessed by external functions.
6) Objects may communicate with each other through functions.
7) New data and functions can be easily added whenever necessary.
8) Follows bottom-up approach in program design.

An object is considered to be a partitioned area of the computer memory that stores data
and set of operations that can access that data. Since, the memory partitions are independent, the
objects can be used in a variety of different programs without modifications. Ex: C++, Java,
Smalltalk, Eiffel.

 OOP’s ENVIRONMENT: It is a new way of solving problems. Instead of moulding


problems to computer environment, the computer adopts the problem. OOP’s is designed around
the data. The operations/functions are designed to0 fit the data.
OOP’s provides the ability to create class hierarchies, instantiate cooperative objects that
collectively work on a problem to produce the solution and send messages between objects.
The power of oops is that it can create modular, reusable code and can perform
composition and modification of existing modules. Flexibility in allowing changing or replacing

-3-
Object Oriented Programming in C++ C.Md.Jamsheed

modules without disturbing other parts of the code. The programming objects are close in
representation to the real world.
 FUNDAMENTAL FEATURES OF OOP’s:
The fundamental features of OOP’s are:
1) Encapsulation 2) Data Abstraction 3) Inheritance 4) Polymorphism 5) Message passing
6) Extensibility 7) Persistence 8) Delegation 9) Genericity 10) Multiple Inheritance.

1) Encapsulation: It is a mechanism that associates the code or functions and the data It
manipulates into a single unit and keeps from external interference and misuse. In C++ this is
supported by a construct called ‘class’. This insulation of the data from direct accesses by the
program is called ‘Data Hiding’.
2) Data abstraction: The technique of creating new data types that are well suited to an
application to be program is known as data abstraction. It refers to the act of representing
essential features without including the background details.
Classes use the concept of abstraction and are defined as a list of abstract attributes and
functions to operate on these attributes. They encapsulate all the essential properties of the
objects that are to be created. Since the classes use the concept of data abstraction, They are
known as abstract data types.(ADTS)[creation of user defined data types].
3) Inheritance: It allows extension and reuse of existing code without having to rewrite the
code from scratch. Inheritance involves the creation of new classes from the existing once. The
new classes thus created are called derived class/child class and the classes from which the new
classes are derived are called base class/parent class. The new derived class inherits the
members of the base class and also adds its own members. Single inheritance refers to deriving a
class from a single base class.
4) Polymorphism: It allows a single name /operator to be associated with different operations
depending on the type of data passed to it.
It allows objects having different internal structures to share the same external interface
[One interface - Multiple methods]. In C++, it is achieved by Function Overloading, Operator
Overloading and Virtual Functions. Polymorphism is used in implementing inheritance.
5) Message passing: It is the process of invoking an operation on an object. In response to a
message, the corresponding method or function is executed in the object. It is supported by C++.
[In C++ when classes are used, the member functions are declared with in the class. Message
passing exists when an object is created for a class. Since, classes are only logical representation
and physical representation of the data is possible only by creation of objects].
6) Extensibility: It is a feature, which allows the extension of functionality of the existing
software components. In C++, this is achieved through Abstract classes and inheritance.
7) Persistence: The phenomenon where the object (data)outlives the program execution time
and exits between execution of a program is known as persistence.

8) Delegation: It is an alternative to class Inheritance. In delegation, two objects are involved in


handling a request. A receive object delegates operation to its delegate .it is analogues to the
child classes sending requests to the parent classes. It creates a view that an object can be a
collection of many objects and the relationship is called the ‘has-a-relationship’ or
‘containership’.
9) Genericity: It is a technique for defining software components that have more than more than
one interpretation depending on the data type of parameters . Thus it allows the declaration of

-4-
Object Oriented Programming in C++ C.Md.Jamsheed

data items without specifying their exact data types. Such unknown data types (generic data
type)are resolved at the time of their usage (function call)based on the data type of parameters.
In c++, genericity is realized through ‘Function Templates’ and ‘Class Templates’.
10) Multiples Inheritance: - The mechanism by which a class is derived from more than one
base class is known as Multiple Inheritance . Instances of classes with multiple inheritance have
instance variables for each of the inherited base classes.
C++ supports all the above 9 features, except persistence .
* BASIC COMPONENTS OF OOP’s:
1) Objects 2) Classes 3) Data hiding 4) Dynamic binding and 5) Message passing / composition.
1) Objects: They are basic run-time entities .the entities are different parts of a problem that
have some physical and conceptual boundaries that separated from each other.
Ex:-book, length ,height, number of pages etc----
They may represent a person, a place, an item or a table of data that the program must
handle. Programming problem is analyzed in terms of objects and the nature of communication
between them. They may also represent user-defined data such as vectors, time and lists.
Every object will have data structures called attributes and behavior called operations.
Ex: consider an object ‘account’ having attributes: accno, acctype, name, balance etc.
and its operation are: deposit, withdraw, enquire etc.
Objects occupy space in memory. Each object contains data and code to manipulate the
data. When a program is executed, the objects interact by sending messages to one another. It is
sufficient to know the type of messages accepted and types of response returned by the object.
Representation of objects: It is done in two ways:

2) Classes: Classes are logical representation of data. The entire set of data and code of an
object can be made a user defined data type with the help of a ‘class’. A Class identifies a set of
similar objects. Objects are variable of class type. Once a class has been defined, any number of
objects belonging to that class can be created. Classes are user defined data types also called
abstract data types. Classes do not occupy any memory space. (Classes = Data Structures +
Functions).

Syntax: Class (User defined type)


{
Data definition; (Logical Representation)
Function Definitions;
};
Ex:- Class Student {
Data: Rollno,
Name; Data Definitions/Data Members

-5-
Object Oriented Programming in C++ C.Md.Jamsheed

Marks;
Functions: Avg ( );
Total ( ); Member functions/
Display ( ); Function definitions

};
If ‘Student’ is a class and Avg ( ), Total ( ) and Display ( ) are its member functions
then: Student A;
A . Avg ( ); will create an object ‘A’ belonging to the class
‘Student’. The class members declared in a class do not define any objects but, only specify
what they will contain.
Creating objects: The declaration of an object is similar to that of a variable of any basic type.
The necessary memory space is allocated to the objects at this state.
Syntax ; < class name > <object name>;
Object name . function name (arguments);
Ex: customer x;
x. deposit ( );

3) Data Hiding: Wrapping up of data and functions into a single unit(class) is called
Encapsulation. The data is not accessible to the outside world and only those functions which
are wrapped in the class can access it.
The functions provide the interface between the objects data and the program. This
insulation of the data from direct access by the program is called ‘Data Hiding’.
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.
Classes encapsulate all the essential properties of the objects that are to be created.
5) Message composition or Message passing: An OOP consists of a set of objects that
communicate with each other. It involves the following steps:
1) Creating classes that define objects and their behavior.
2) Creating objects from class definitions.
3) Establishing communication among objects.
Objects communicate with each other by sending and receiving information. A message
for an object is a request for execution of a procedure. It invokes a function (procedure) in the
receiving object that generates the desired result.
Message passing involves name of the object, the name of the function (message) and
the information to be sent.
Ex: Employee . salary(name);

Object message information


4) Dynamic binding: It refers to the linking of a procedure call to the code to be executed in
response to the call. Dynamic binding means that the given procedures call is not known until
the time of call at run time. It is associated with polymorphism and inheritance.
* Benefits of oop:
1) Through Inheritance, redundant code can be eliminated and the use of existing
classes can be extended.

-6-
Object Oriented Programming in C++ C.Md.Jamsheed

2) Programs can be build from the standard working modules that communicate with
one another rather than having to start writing the code from scratch. This leads to
saving of development time and higher productivity.
3) The principle of data hiding helps the programmer to build secure program that
cannot be invaded by code in other parts of the program.
4) It is possible to have multiple instances of and object to co-exist without any
interference.
5) It is easy to partition the work in a project based on objects.
6) The data centered design approach enables us to capture more details of a model in
implement able form.
7) Object oriented systems can be easily upgraded from small to large systems.
8) Message passing techniques for communication between objects makes the interface
descriptions with external systems much simples.
9) Software complexity can be easily managed.
Disadvantages
1) Compiler overhead. 2) Runtime overhead.
3) Re-orientation of software developer to object oriented thinking.
4) Requires the mastery over the area:- Software Engineering and Programming
Methodologies.
Dynamic binding mechanism is the major disadvantage of OOP.
 POPULAR OOP’s LANGUAGES:
Some popular OOP languages are C++, Small talk, SIMULA, Eiffel, and java.
1) C++: C++ is evolved from a dialect C known as ‘C with classes’. It also includes the
components from SIMULA 67 and ALGOL68. It provides compile time type checking and
support for modular and OOP. Some of the most prominent features of C++ are Classes,
Operator and Function Overloading, Free store management, Constant types, References, Inline
functions, Inheritance, Virtual functions, Streams for console and file manipulation, Templates
and Exceptions handling.

2) SMALL TALK: It is the first OO language. Besides being a language, it has a development
environment. Objects are called instance variables and they are dynamic. Variables are untyped
and can hold objects of any class. New objects are created using the message passing
mechanism. All attributes are private to the class and there is no way to restrict the operations of
a class. All operations are public.
Support Inheritance, but do not support Multiple Inheritance. All methods can be
overridden. Small talk is weakly typed. It has a rich class library designed to be extended and
adapted by adding subclass.
3) Charm C++: Charm C++ is portable, concurrent operating system based on C++. It is an
extension of C++ and provides a clear separation between sequential and parallel objects.
The language supports Multiple Inheritance, Dynamic binding, overloading,
Strong typing and reuse of parallel objects. Sharing of information between parallel objects is
supported (Shared memory mechanism).
4) Java: It is a Simple, Object oriented, Portable, architectural neutral, robust, secure, multi-
threaded
and high performance programming language. It is intended for the development of OO network
based software for Internet applications.
Doesn’t support features of C++ such as Pointers, Security and Advanced
networking without compromising on performance. Java application byte code runs on any
platform without any modification or recompilation.

-7-
Object Oriented Programming in C++ C.Md.Jamsheed

 APPLICATIONS OF OOP’s: Some promising applications of OOP includes the


following:
1. Real time systems
2. Simulation and Modeling
3. Object-oriented databases.
4. Hypertext, Hypermedia and Eexpertext.
5. AI and expert systems.
6. Neural networks and parallel programming.
7. Decision support and office automation systems.
8. CIM/CAM/CAD systems.
 EVOLUTUION OF C++: Bjarne Stroustrup developed C++ at AT&T Bell Laboratories in
Murray Hill, New Jersey USA in 1980 as an extension of C. C++ is evolved from a dialect C
known as ‘C with Classes’ as a language for writing effective event driven simulation. Several
key ideas were borrowed from SIMULA 67 and ALGOL 68 Programming Languages. ‘C with
Classes’ lacked Operator Overloading and Virtual Functions, References and these are
overcome in C++. Later in 1983, the name was changed to C++ by Rick Mascitti. C++ is an
augmented (incremented) version pf C. C++ is a superset of C.
In 1990’s the language underwent a number of improvements and changes. In November
1997, the ANSI/ISO standards committee standardized these changes and added several new
features to the language specifications.
The OO features in C++ allow programmers to build large programs with clearity,
extensibility and ease of maintenance. The addition of new features has transformed C from a
language that currently facilitates Top-Down, Structured design, to one that provides Bottom-
Up, Object Oriented (OO) design. C++ corrects most of the deficiencies of C by offering
improved Compile time type checking and support for modular and OOP.

 ELEMENTS OF OOP:
Object Oriented programming is well suited paradigm for the following:
1) Modeling the real world problem as close as possible to the user’s
perspective.
2) Constructing reusable software components and easily extendable
libraries.
3) Easily modifying the extending implementations of components without
having to recode every thing from scratch.
4) Interacting easily with computational environment using familiar
metaphors.
The language quality and its elements is judged by 12 criteria. They are:
1) A well-defined syntactic and semantic structure 2) Reliability 3) Fast translation 4) Efficient
Object Code 5) Orthognality (Having few basic features, each of which is separately
understandable) 6) Machine Independent 7) Provability 8) Generality 9) Consistency with
commonly used notations 10) Subset 11) Uniformity 12) Extensibility.

-8-
Object Oriented Programming in C++ C.Md.Jamsheed

 DATA TYPES in C++: Data types in C++ can be classified under various categories. C++
supports a wide variety of data types and the programmer can select the type appropriate to the
need of the application.

Both c and c++ compilers supports all the built in data types. With the exception of
‘void’, the basic data types may have several modifiers of qualifiers preceding them to serve the
need of various situations. The modifiers signed, Unsigned, Long and Short may be applied to
char and int basic data types. The modifier ‘long’ may be applied to double.
The type void was introduces in ANSI C. Two normal uses of void are:
1. To specify the return type of a function when it is not returning any value an and
2. To indicate an empty argument list to a function.
Example: void function 1(void);
 Size and Range of C++ Basic Data Types: ( For 16 bit word machine)
TYPE BYTES RANGE .

Char 1 -128 to 127


Unsigned char 1 0 to 255
Signed char 1 -128 to 127
Int 2 -32768 to 32767
Unsigned int 2 0 to 65535
Signed int 2 -31768 to 32767
Short int 2 -31768 to 32767
Unsigned short int 2 0 to 65535
Signed short int 2 -32768 to 32767
Long int 4 -2147483648 to 2147483647
Signed long int 4 -2147483648 to 2147483647
Un signed long int 4 0 to 4294967295
Float 4 3.4E-38 to 3.4E+38
Double 8 1.7E-308 to 1.7E+308
Long double 10 3.4E-4932 to 1.1E+4932

-9-
Object Oriented Programming in C++ C.Md.Jamsheed

 Character Set: The C++ Character set consists of the uppercase and lowercase alphabets,
digits, special characters and white spaces.
a) Alphabet:
Uppercase: A, B, C,-------- Z.
Lowercase: a, b, c, ----------,z.
b) Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
c) Special Characters:
, Comma < Opening angle bracket > Closing angle
. Period _ Underscore ( Left Parenthesis
; Semicolon $ Dollar Sign ) Right Parenthesis
: Colon % Percent Sign [ Left Bracket
# Number Sign ? Quotation mark ] Right Bracket
‘ Apostrophe & Ampersand { Left brace
“ Quotation Mark ^ Caret } Right brace
| Vertical bar * Asterisk / Slash
~ Tild - Minus Sign \ Back Slash
White spaces: Blank space-,new line carriage return
Form feed horizontal tab vertical tab
+ Plus Sign

 SINGLE LINE COMMENT:


C++ introduces a new comment symbol ‘// ‘. The comments starts with a double slash
symbol and terminates at the end of the line. A comment may start anywhere in the line. There
is no closing symbol for comment. The compiler ignores the complete line starting from ‘//’
character pair.
The double slash comment is basically a single line comment. Single line comment runs
across only one line in a source program.
Ex: 1) Welcome to III-B.Com. 2) This is a single line comment.
Actual Syntax:
[Any C++ statement] // This is a C++ comment.

Any C++ executable statement Comment symbol Single line comment statement

The C style comment symbols /* , */ are also valid and are more suitable for multi line
comments. Multi line comments run across two or more lines in a source program.
Ex: /* This is an example of
C++ Program to illustrate
Multi line comment */
Note: We cannot insert a comment with in a comment and a comment cannot be inserted with
in the text of a program line.
Ex: 1) /* This is a program for addition /* Make use of + Operator */ */  Invalid.
2) for(j=0; j<n; /* loop n times */ j++) – Invalid.

 STRUCTURE OF C++ PROGRAM:


The structure of a C++ program is as follows:

1. // Printing a message -- Comment


2. # include <iostream.h> -- Preprocessor directive
3. Void main() -- function declaration
4. { -- function begin

- 10 -
Object Oriented Programming in C++ C.Md.Jamsheed

5. ----------
Program body -- body of the function main
----------
6. } -- main function end
The function main ( ) is designated as the starting point of the program execution and is
defined by the user. It cannot be overloaded and its syntax type is implementation dependent.
The header file ioatream.h supports streams programming features by including
predefined stream objects. It contains declarations that are needed by [cout and cin] i.e input and
output streams.
Creating the Source File:
C++ programs are create using any text editor. The process of compiling and linking
depends upon the operating system. Ex: Turbo C++, ANSI C++.

 I/O in C++:
a) Output Operator: Just as printf in C, C++ uses a predefined object called ‘cout’ for the
output statement.
Ex: Cout<<” This is an output statement”;
This causes the string in quotation marks to be displayed on the screen. This statement
has two features, cout and <<. The identifier ‘cout’ is a predefined object that represents the
standard output streams in C++.
The operator ‘<<’ is called the ‘insertion’ or ‘put to’ operator. It inserts or sends the
contents of the variable to its object.

The directive #include <iostream.h> causes the preprocessor to add the contents
of the iostream file to the program. It contains declaration for the identifier cout and the operator
<<. It should be included at the beginning of all programs that use Input/Output statements.
b) Input Operator: As scanf in C, C++ uses ‘cin’ for the input statement.
It causes the program to wait for the user to type in a number. The number keyed
in is placed in the variable. The identifier ‘cin’ is a predefined object in C++ that corresponds to
the standard input stream. This stream represents the keyboard.

The operator is known as ‘extraction’ operator or ‘getfrom’ operator. It extracts


or takes values from the keyboard and assigns it to the variable.
 STREAMS IN C++:
I/O system supplies an interface to the programmer that is independent of the
actual device being accessed. This interface is known as Streams. Streams resemble the
producer and the consumer model. The producer produces the items to be consumed by the user.

- 11 -
Object Oriented Programming in C++ C.Md.Jamsheed

A stream is a sequence of bytes. It acts either as a source from which the input
data can be obtained or as a destination to which the output data can be sent. The source stream
that provides data to the program is called the ‘Input stream’ and the destination stream that
receives output from the program is called the ‘Output stream’. In other words, a program
extracts the bytes from an Input stream and inserts bytes into an Output stream.

 C++ Stream Classes:


The C++ I/O system contains a hierarchy of classes that are used to manipulate both
the console and disk files, called stream classes. The stream classes are declared in the header
file <iostream.h>. This file should be included in all programs that communicate with the
console unit.

The I/O stream facility of C++ provides an easy means to perform I/O.

Stream classes for console I/O operations:


1) ios class: It is a base class for istream(input stream) and ostream(output stream). The istream
and ostream are in true, base classes for iostream(input/output stream).
The ios class provides the basic support for constants and member functions
necessary for handling formatted and unformatted I/O operation.
a) istream (input stream)  does formatted input.
b) ostream(output stream)  does formatted output.
c) iostream(input/output stream)  does formatted/unformatted input and
output.

- 12 -
Object Oriented Programming in C++ C.Md.Jamsheed

The ios class contains a pointer to a buffer object ’Streambuf’ that provides an
abstraction for communicating to a physical device and classes derived from it deal with files,
memory. The ios communicates to the streambuf, which maintains information on the state of
the streambuf(good, bad, eof, etc) and maintains flags used by the istream and ostream.
2) istream class: It is derived class of ios, and hence inherits the properties of ios. It defines
input functions such as get( ), getline( ), and read( ). In addition , it contains overloaded
extraction operator”>”, to read data from a standard input device to the memory items. It uses
predefined stream ‘cin’ for this.
3) ostream class: It is derived from ios class, and hence inherits the properties of ios. It defines
output functions such a write( ),put( ). In addition, it contains overloaded insertion operator
“<<” to write data from memory items to a standard output device. It uses predefined stream
‘cout’ for this.
4) iostream class: It is derived from multiple base classes, istreams and ostreams, which are
inturn inherited from the class ios. It provides facility for handling both input and output
streams, and supports all the operations provided by the istream and ostream classes.
The three classes namely, istream_withassign, ostram_withassign and
iostream_with assign add assignment operators to these classes.

 TOKENS IN C++: C++ program consists of many elements or words which are identified
by the compiler as Tokens. Tokens are categorized as follows:

Tokens supported in c++ can be categorized as identifiers, keywords, variables,


constants, special characters and operators.
 IDENTIFIERS:
Identifiers refer to the names of variables, functions, arrays, symbolic constants, classes
etc. In a c++ program every word can be classified as an identifier or a keyword. The following
are the rules for defining identifiers:
1. Identifier name is formed by using alphabet, or underscore characters.
2. Identifier names must begin with an alphabet or underscore characters.
3. Identifier name cannot start with a digit.
4. The maximum number of characters used in forming an identifier must not exceed 32
characters.
5. The upper case and Lower case letters are treated differently.

 KEYWORDS:
C++ has standard identifiers called keywords. Keywords declared in C++ language and
have a predefined meaning. They are explicitly reserved identifiers and cannot be used as names
for program variables or other user defined program elements.

Keywords common to C and C++:

- 13 -
Object Oriented Programming in C++ C.Md.Jamsheed

Auto double int struct


Break else long switch
Case enum register typedef
Char extern return union
Constant float short unsigned
Continue for signed void
Default goto sizeof volatile
Do if static while
C++ specific keywords:
These are the keywords primarily deal with classes, templates and exeption handily.
Asm new template
Catch operator this
Class private throw
Delete protected try
Friend public virtual
Inline
 Variables: A variable is an entity whose values can be changed during program execution
and is known to the program by a name. A variable definition reserves memory location for data
storage, and associates it with a symbolic name. Its value can be changed during the execution
of program. A variable can hold only one value at a time during the program execution. It must
be defined before using it in a program.
Syntax: Data type <Variable name>; Memory location : machine
view.
Data type < var1, var2, var3, -------var n>; Value : data stored in memory
location.

Ex: int a;
int x, y, z;
float tot, len;

Variable initialization:
A variable can be assigned with a value during its definition or during the program
execution. The assignment operator “=” is used in both the cases.
Syntax: Data type variable name = constant value; or)
Data type variable name (constant value);
Ex: Int a=20; (or ) int a (20);
Float c=12.9; (or) float c (12.9);
Variable can be initialized, by using any valid expression at run time. The general format
is:
Syntax: Variable_ name = expression;
Ex: int a = c+d-5;

 LITERALS-CONSTANTQUALIFIERS: Literals are constants, to which symbolic names


are associated. C++ provides three ways for defining constants.
a) #define pre-processors directive.
b) Enumerated data types.
c) Const keyword.

- 14 -
Object Oriented Programming in C++ C.Md.Jamsheed

C++ supports a new constant qualifier for defining a variable, whose value cannot be
changed once; it is assigned with a value at the time of variable definition.
The qualifier is used in c++ to define such a variable is the ‘const’ qualifier .If data type
is not declared, it is considered as ’int’ by default. Note: Literal constants do not nave memory
locations.
Syntax: Const <data type> variable name = constant value;
The ‘Const’ is a keyword. The data type can be a standard or user defined data type.
Ex: const float PI = 3.1452;
Const char Book_name=”OOP’s with C++”;

 ENUMARATED DATA TYPES: An enumerated data type is an user defined type which
provides a way for attaching numbers to names, thereby increasing the comprehensibility of the
code. The key word ‘enum’ automatically enumerates a list of words by assigning them values
0,1,2 and so on. This facility provides an alternative means for creating symbolic constants.

Syntax: enum shape {circle , square , triangle};


Enum color {red , blue , green , yellow};
Enum posotion { off , on};
In c++, the tag names shape, color, position become new type names. By using there tag names,
we can declare new variables.
Shape ellipse;
Color background;
Then we can set further in programs as :
Color background=blue;
program for variable definition and assignment c1.cpp //

#include<iostream.h>

void main()
{
int a, b;
int c=20;
float d;
a=c;
b= c+20;
d= 20.5;

cout << “a =” <<a <<”\n”;


cout <<” b = “ <<b << “\n”;
cout << “ c = “<<c <<“\n” ;
cout <<” d = “ << d << “\n”;
}
constants : a constant does not change its value during the entire execution of the program.
They can be classified as.

1. integer
2. floating point

- 15 -
Object Oriented Programming in C++ C.Md.Jamsheed

3. character
4. string literals.

1. integer constants : C++ allows to represent the integer constants in three forms. They
are octal, decimal and hexadecimal.

(a) octal system (base 8) : octal numbers are specified with a leading zero, rest of
the digits being between 0 and 7. for example : 0175 is an integer constant
specified in octal whose base –10 value is 125.
(b) Decimal system (base 10) : it is the most commonly used system. A number in
this system is represented by using digits 0_10. for instance, 175 is an integer
constant with base 10.
(c) Hexadecimal system (base 16) : hexadecimal numbers are specified with 0x or
0x in the beginning. For example oxal is an integer constant specified in
hexadecimal whose base_10 on decimal value is 161.

Examples : 1. unsigned integer constants 56789 U , 56789 u.


2. long integer constant 7689909 L.

2. floating point constants : floating point constants have a decimal point or an exponent
sign, or both.

(a) decimal notation : here the number is represented as a whole number, followed
by a decimal point and a fractional part. It is possible to omit digit before and
after the decimal point.

Example of valid floating point constants :

125.45 241. .976 -.71 +.5

exponential notation : exponential notation is useful in representing numbers whose


magnitudes are not very large or not very small. The exponential notation consists of a
mantissa and an exponent. The exponent is positive unless proceeded by a minus sign. The
number 231.78 can also be written as 0.23178e3, representing the number
0.23178 * 10E3. The sequence of digits 23178 in this case after the decimal point is called the
mantissa, and 3 is called the exponent.

For example, the number 75000000000 can be written as 75e9 or 0.75e11, the number
0.00000000045 can be written as 0.45e-9.

Ex : 2000.0434 3.4e4 3E8

(3) Character constants : A character constant is enclosed within single quotes.

Ex : ‘ a ‘ , ‘ 5 ‘ or ‘ \n ‘ invalid constants ‘ ab ‘ , ‘ 54 ‘ .

Operator meaning
`
\a beep
\b backspace
\f formfeed

- 16 -
Object Oriented Programming in C++ C.Md.Jamsheed

\n new line
\t horizontal tab
\\ back slash
\‘ single quote
\” double quote
\v vertical tab
\? Question mark
\0 null
\0ooo code specified in octal
\xhh code specified hexadecimal

(4) string literals : A string literals is a sequence of characters enclosed in double quotes. The
characters may be letters, numbers escape sequences on blank spaces. To make it easier string
constants are concatenated at compile time.

For example, the strings:

“ C++ is the best “ and


“ C++ is “ “ the best “ are the same.
Characters and character strings :
.
A character variable can hold a single character. For example, the statement char
code=’R’; assigns the character constant R to the variable code. The value stored in the
variable code is the ASCII equivalent of the character R. the character constant is enclosed in a
pair of single quotes and each character representation requires n8 bits(one byte)
A sequence of characters is called a string. String constants are enclosed in
double quotes as follows: “hello world”.
String constants are useful while converting some messages to the user.
For ex: the statement.
Cout<< “ I love C++ programming.

 FORMATTED and UNFORMATTED DATA:


a) Unformatted I/O operations:
Overloaded Operators << and >>: The pre-defined stream objects cin and cout are used for
the input and output of various types. This has been made possible by overloading the operators
>> and << to recognize all the basic C++ data types. The >> operator is overloaded in the
‘istream’ class and << operator is overloaded in the ‘ostream’ class.
The general format for reading data from the keyboard is as follows:
Cin>>variable1>>variable2>> ------ >>variable n; the variables are valid C++ variable
names that have been declared already.
The general format for reading data from the keyboard is as follows:
Cout<<item1<<item2<< --------- <<item n; the items item1 through item n may be
variables or constants of basic type.
* Put( ) and get( ) functions: The classes istream and ostream defines two member functions
get( ) and put ( ) respectively to handle ‘string character I/O operations’. Both the functions can
fetch a white space character including the blank space, tab, and new line characters.
a) get( ): The function get( ) is a member function of the input stream class ‘istream’ and is
used to read a single character from the input device. The function get( ) has 2 versions with the
following prototypes:

- 17 -
Object Oriented Programming in C++ C.Md.Jamsheed

1) void get(char *);  get(char)


2) void/int get(void);  get( )
The get(void) version returns the input character and the get(char *) version assigns the
input character to its arguments. Since these functions are member functions of the input stream
classes, we must invoke them using an appropriate object. These two functions can be used to
perform input operations either using the pre-defined object ‘cin’ or an user defined object of the
‘istream class’.
(cin.get(c) or c=cin.get( )).

Program // read characters using get( ) of istream


#include<iostream.h>
void main(0
{char c; Output:
cin.get( c); //get a character from keyboard and assign it to c. hello world
while(c!=’\n’) hello world

{
cout<<c; //display the character on the screen.
cin.get(c) // get another character or read another character.
}
}
This code always reads and displays a line of text (terminated by a new line
character). I cin.get( c) statement is replaced by the statement cin>>c; the while loop will not
work properly since, the operator >> can be used to read a character but it will skip the
whitespaces and newline character.

The get(void) version can also be used in the above program as follows:
-------
char c;
c = cin.get( ); // cin.get( c) is replaced.
It reads a single character and return the same result. The value returned by the function
get( ) is assigned to the character variable c.

Since these functions are member functions of the input stream classes, we must invoke them
using an appropriate object

Unit-II - Operators and Expressions,Control Structures

- 18 -
Object Oriented Programming in C++ C.Md.Jamsheed

Types of operators: In C++, operators can be classified into various categories based on
their utility and action as follows.

1. Arithmetic operators.
2. Relational operators.
3. Logical operators.
4. Assignment operator.
5. Increment and decrement operators.
6. Conditional operators
7. Bitwise operators.
8. Special operators.

Expression: An expression is a combination of variable, constants and operators written


according to the syntax of the language. In C++ every expression results in some values of a
valid data type, that can be assigned to a values. The following are some of the valid
expression: a + b;
A + 200 + 40;
C + b * z;
Z + 20;
Total + 20 + c/3;
Expression having operands of different data types are called mixed mode expressions. Consider
the following statements.
Int a, c;
Float d, e;
The expression (a + d + e + c) is called mixed mode expression, since it contains variables of
types; integer and floating point.
1. arithmetic operators: the C++ language has both unary and binary arithmetic operators.
Unary operators are those which operate on a single operand whereas, binary operators
operates on two operands. The arithmetic operators can operate on any built in data types.

+ addition (or)unary plus.


- subtraction (or) unary minus.
* multiplication.
/ division.
% modulo division.
Unary minus operator (negation) : the unary minus operators can be used to negate the
values of a variable. It is also used to specify the negative number, and a (-) sign is prefixed to
the number.

For example: int x = 5;


Y = -x;
The values of ‘x’ after negation is assigned to ‘y’ ie y becomes –5.

Binary operators: binary operators such as +, -, * etc required two operands of standard
data types. Depending on the data types of the operands, these operators perform either integer
or floating point arithmetic operation.

Integer arithmetic: when the two operands say x and y are defined as integers, any
arithmetic operation performed on these operands is called integer arithmetic, which always
yields an integer result.

- 19 -
Object Oriented Programming in C++ C.Md.Jamsheed

Example: let x and y defined by


Int x = 16, y = 5;
Then the integer arithmetic operations yield as follows:
X + y = 21, x – y = 11, x * y = 80;
X / y = 3 _ the result is truncated ie the decimal part.
X % y = 1 _the result is remainder of integer division.

Floating point arithmetic: floating point arithmetic involves operands of real type in
decimal or exponential notation. The floating point result are rounded off to the number of
significant digits specified and hence the final value is only an approximation of the correct
result. The remainder operator ‘ % ‘ is not applicable to floating point operands.
Ex: float a=14.0, b=4.0
P, q, r be floating point variables then
P= a/b = 3.500000
Q= b/a = 0.285714
R= a + b = 18.00000
Mixed mode arithmetic: in mixed mode arithmetic if either one of the operands is real, the
resultant value is always a real value. For example , 35/5.0=7.0. here , 5.0 is a double constant,
35 is converted to a double and the result is also a double.
The expression x % y produces the remainder when x is divided by y.
// program illustrating the use of modulus operator //
#include <iostream.h>
void main()
{
int num, dem;
float res, rem;
cout <<”enter numerator:”;
cin>>num;
cout <<”enter denominator:”;
cin>>dem;
res = num/dem;
rem = num % dem;
cout <<”num << “ / “ <<dem << “ = “ << res << endl;
cout <<”num” << “ % “ << dem << “ = “ << rem << endl;
}
output:
enter numerator : 12
enter denominator : 5
12/5 = 2
12%5 = 2

//swapping of two numbers without using temporary variable//


#include < iostream.h >
void main ()
{
int a, b ;
cout <<” enter two integers a & b “;
cin >> a >>b;
a = a + b;

- 20 -
Object Oriented Programming in C++ C.Md.Jamsheed

b = a – b;
a = a – b;
cout << “ swapping of 2 numbers “ << a << “ “ << b;
}
out put:
enter two integers a & b : 20, 30
swapping of 2 numbers : 30, 20

2. Relational operators: a relational operator is used to make comparisons between two


expressions. All these operators are binary and require two operands. Logically similar
quantities are often compared for taking decisions. These comparisons can be done with the
help of relational operators. Each one of these operators compares its left hand side operand
with its right hand side operand. The whole expression involving the relational operator
then evaluates to an integer. It evaluates to zero if the condition is false and non_ zero if the
condition is true.
Operator meaning
< less than.
> greater than
<= less than or equal to.
>= greater than or equal to
== equal to
!= not equal to

// Program illustrating relational operator usage//


# include <iostream.h>
void main ()
{
int age, age1;
cout <<”enter age1”;
cin >>age1;
cout <<” enter age2”;
cin>>age2;
if (age1==age2)
cout << “ ages are equal “;
else
cout << “ ages are different”;
}

out put:
enter age1 : 23;
enter age 2 : 23;
ages are equal.

3. logical operators: any expression that evaluates to zero denotes a FALSE logical
condition, and that evaluating to non zero value denotes a TRUE logical condition. Logical
operators are useful in combining one or more conditions. C++ has 3 logical operators.
Operator meaning
&& logical AND
|| logical ARE
! logical NOT

- 21 -
Object Oriented Programming in C++ C.Md.Jamsheed

the first two operators && and || are binary, where as ! is a unary operator and is used to negate
a condition.
Logical AND: for example a>b && x == 10.
The expression on the left side is a>b and that on the right is x == 10. The whole expression
evaluates to true only if both expressions are true.

Logical OR: for example a < x // a < y


The expressio9n is true if one of them is true, or if both of them are true I,e if the value of ‘a’ is
less than that of x, or if it is less than y. it is true when a is less than x and y.

Logical NOT: The !(not) operator takes a single expression and evaluates to true if the
expression is false, and evaluates to false if the expression is true. It just reverses the value of
the expression. For example consider.
! ( x > = y ) it is same as x > y and for
if ( a = = 0 ) means if ( ! a )
the expression ! a evaluates to true if the variable a holds zero, false otherwise.

A b ~a ~b a && b a // b
F F T T F F
F T T F F T
T F F T F T
T T F F T T
The unary negation operator ( ! ) has a higher precedence among three, followed by the logical
AND ( && ) operator and then the logical OR ( || ) operator, and are evaluated from left to right.

// program that detects whether a year is leap or not //


# include <iostream.h >
void main ()
{
int year;
cout << “ enter any year “ ;
cin>> year;
if (( year % 4 == 0 && year % 100 ! = 0 ) || ( year % 400 == 0 ) )
cout << year << “ is a leap year “;
else
cout << year << “ is not a leap year “ ;
}
out put :
enter year 1996
1996 is a leap year.

4. assignment operator: the equal ( = ) sign is used for assigning a value to a variable. It
has the following syntax : variable = expression ;
the left hand side has to be a variable ( often called l value ) and the right hand side has to be a
valid expression ( r value ) . examples are
a = 3200;
b = x + 10 * c ;
c = sqrt ( 40.5 ) ;
// program which converts centigrade to Fahrenheit & vice versa //
# include <iostream . h>
void main ()

- 22 -
Object Oriented Programming in C++ C.Md.Jamsheed

{
float c, f;
cout << “ enter temperature in Celsius : “ ;
cin>>c;
f = 1.8 * c + 32 ;
cout << “ equivalent Fahrenheit = “ <<f << endl;
cout << “ enter temperature in Fahrenheit “ ;
cin>>f;
c = ( f-32) / 1.8;
cout << “ equivalent Celsius = “ << c;
}
5. increment and decrement operators : C++ language offers two unusual unary
operators for incrementing and decrementing variables. These are ++ and – operators and
are known as increment and decrement operators respectively. These operators increase on
decrease the value of a variable on which they can be used as prefix or postfix and their
meaning changes accordingly. When used as a prefix, the value of the variable is
incremented, decremented before being used in the expression. But when used as a postfix,
it’s value is first used in the expression and then the value is incremented / decremented.
The syntax of the operators is given below.
++ variable name
variable name ++
-- variable name
variable name –
The operator ++ adds 1 to the operand and – subtracts 1 from the operand.
6. Conditional operator ( ternary pair ) : An alternate method to using a simple if
else construct is the conditional expression operator ( ? : ). It is also called the ternary pair,
which operates on three operands. It has the following
Syntax : expression 1 ? expression 2 : expression 3.
Here expression is evaluated first ; if it is true, then the value of expression 2 is the result ;
otherwise the expression 3 is the result. The if else construct.
If ( a > b )
Z=a;
Else
Z=b;
Which finds the maximum of a and b; it can be alternatively realized by using .
Z=(a>b)?a:b;

// program finding the maximum using conditional operator //


# include <iostream . h >
void main ()
{
int a, b, larger ;
cout << “ enter two numbers : “ ;
cin >> a >> b ;
larger = a > b ? a : b ;
cout << “ the larger of two numbers is : “ << larger ;
}

7. bit wise operators : The support of bit wise manipulation on integer operands is
useful in many applications.

- 23 -
Object Oriented Programming in C++ C.Md.Jamsheed

The binary representation of a is 0000 0000 0000 1101


The binary representation of b is 0000 0000 0000 0111

Operator meaning
& bit wise AND
| bit wise OR
^ bit wise EX-OR
~ bit wise complement
<< shift left
>> shift right
( I ) logical bit wise operators : logical bit wise operators perform logical operators such as
AND , OR, EX-OR, NOT between corresponding bits of operands ( if binary ) and negation of
bits ( if unary ).
Unary operator ( one’s compliment ) ( ~ ) : The complement operator causes the bits of its
operands to be inverted I,e 1 becomes 0 & 0 becomes 1 . for example the largest possible
number, which can be stored in an unsigned integer can be found as follows. When one’s
complement operator is applied in this word holding zero, all the bits will be inverted to ones &
new value becomes largest possible number.

// program detects largest possible unsigned integer //


# include < iostream . h>
int main ()
{
unsigned u = 0 ;
cout <, “ value before conversion : “ << u << endl ;
u=~u;
cout << “ value after conversion : “ << u << endl ;
}

binary logical bit wise operators : There are three logical binary bit wise operators & ( and ) , 1
( or ) , and ^ ( exclusive or ).

( a ) bit wise AND : The statement c = a & b ; makes use of the bit wise AND operator.
After this statement is executed, each bit in C will be 1 only if the corresponding bits in both a
and b are 1.
Bit wise AND operator : a & b
A 0000 0000 0000 1101
B 0000 0000 0000 0111

A&B 0000 0000 0000 0101

( b ) Bit wise OR : The statement c = a / b ; makes use of the bit wise OR operator. After
this statement is executed, a bit in C will be 1 whenever atleast one of the corresponding bits in
either a or b is 1 .
bit wise OR operator : a / b
a 0000 0000 0000 1101
b 0000 0000 0000 0111

- 24 -
Object Oriented Programming in C++ C.Md.Jamsheed

a/b 0000 0000 0000 1111

( c) Bit wise xor : The statement c = a ^ b ; makes use of the bit wise xor operator. After this
statement will be executed, a bit in C will be 1 whenever the corresponding bits in a and b differ.
Bit wise EX-OR operator a ^ b
A 0000 0000 0000 1101
B 0000 0000 0000 0111

A ^ B 0000 0000 0000 1010

Shift operator : there are two shift operators in C++ : left shift ( << ) and right shift ( >>).
There are binary operators and have the following syntax :
Operand << count for left shift
Operand >> count for right shift

( a ) left shift operator ( << ) : Consider the statement c = a << 3 ;


the value in the integer a is shifted left by three bit position.
Left shift <<
Drop off 0000 0000 0000 1101 insert as
After left _ bit shift by 3 places ( a << 3 )

0000 0000 0110 1000

( b ) right shift operator ( >> ) : consider the statement c= a>> 2 ;


The value of a shifted right nby 2 positions
Right shift >>
Insert as 0000 0000 0000 1101 drop off
After right shift by 2 places ( a >> 2 )
0000 0000 0000 0011
( 8 ) special operators : Some of the special operators included by C++ are sizeof and
comma operators.
( a ) comma operator : A set of expression separated by commas is a valid construct in C++. It
links the related expressions together. Expressions linked using comma operator are evaluated
from left to right and the value of the rightmost expression is the result. For example I=(j
= 3, j + 2 ) ;
The right hand side consists of two expressions separated by comma. The expressions are
evaluated from left to right. First the value 3 is assigned to ‘j’ then expression ‘j + 2’ is
evaluated. The value of the right most expression.
( b ) size of operator : The operator size of returns the number of bytes required a data type on
variable. It has the following forms :
sizeof ( datatype );
sizeof ( variable );
The data type can be standard on user defined data type. For example :
Int I, j ;
Float c;
Sizeof ( int ) returns 2 or 4 depending on compiler
Sizeof ( float ) returns 4
Sizeof ( c ) returns 4

- 25 -
Object Oriented Programming in C++ C.Md.Jamsheed

Typedef statement : The typedef statement is used to give new names to existing data types. It
allows the user to declare an identifier to represent an existing data type having the following
syntax :
Typedef type identifier ;
Where type refers to an existing data type and identifier refers to the new name given to the data
type for example, the statement
Typedef unsigned long ulong ;
Declares ulong to be a new type, equivalent to unsigned long. It can be used just like any
standard data type in the program. For example, the statement
Ulong u;
Control flow
The C++ language offers a number of control flow statements : for, while, do-while, if-else,
else-if, switch, goto. Although all of them can perform operation such as looping or branching,
each one of them is convenient for a particular requirement. The control flow statements can be
broadly categorized as branching and looping statements.
Statements and block :
An expression such as a = 1000, x++, or cout << “ Hi”; when followed by the semicolon
becomes a statement. For example, the following
A = 1000 ;]
X ++ ;
Cout << “ Hi “ ;
Are treated as C++ statements. In C++ the semicolon is a statement terminates or deliminator.
C++ allows grouping of statements, which have to be treated as an entity and the
resulting group is called compound statement or block. It consists of declarations, definitions
and statements enclosed within braces { and } as follows :
{
int a ;
int b = 10 ;
a = b + 50 ;
}
any variable defined within block is local to the block and it is not visible outside the block.
Blocks are very useful when branching or looping action is to be applied on a set of statements.
Branching statements : Following are the branching statements supported by C++.
( a ) if statement.
( b ) if _ else statement.
( c ) switch statement.
( d ) goto statement.
( a ) if statement :
The if constructs is a powerful decision making statement which is used to control the sequence
of the execution of statements. It alters the sequential execution using the following syntax :
If ( text _ expression )
Statements ;
The test expression should always be enclosed in parenthesis. It test expression is true ( non
zero ) , then the statement immediately following it is executed other wise, control passes to the
next statement following if construct.

// use of if statement
# include <iostream.h>
void main ()
{

- 26 -
Object Oriented Programming in C++ C.Md.Jamsheed

int age ;
cout << “ enter your age : “ ;
cin>> age;
if ( age > 12 && age < 20 )
cout << “ you are teenage person : “ <<endl;
}
compound statement with if : In the if constructs, the if part can be represented by a compound
statement as follows :
if ( test _ expression )
{
statement 1 ;
statement 2 ;
}
In this case, when test _ expression is true, the statements enclosed with the curly braces,
representing a compound statement are executed.

// use of if statement and data validation


# include <iostream.h>
void main ()
{
int age ;
cout << “ enter your age : “;
cin>>age ;
if ( age < 0 )
{
cout << “ I am sorry : “ <<endl;
cout << “ age can never be negative “ ;
return ; // terminate program
}
if ( age > 12 && age < 20 )
cout << “ you are a teenaged person “;
}

// program finding the largest of 3 numbers //


# include <iostream.h>
void main ()
{
float a, b, c, big;
cout << “ enter 3 floating point numbers : “ ;
cin >>a>>b>>c;
big = a ;
if ( b > big )
sbig = b ;
if ( c > big )
big = c ;
cout << “ the largest of 3 numbers is “ <<big ;
}

( b)

- 27 -
Object Oriented Programming in C++ C.Md.Jamsheed

if else statement : The if else statement will execute a single statement or a group of statements,
when the test expression fails. C++ provides the if else construct to perform some action even
the test expression fails.
If ( expression )
{
statement 1 ;
}
else
{
statement 2 ;
}

// use of if else statement //


#include<iostream.h>
void main()
{
int age ;
cout << “ enter your age “ ;
cin >>age ;
if ( age > 12 && age < 20 )
cout << “ you are a teenage person “;
else
cout << “ you are not a teenaged person “ ;
}
compound statement with if else : In the if else construct, the if part, or else part, or both can
have a compound statement as follows :
if ( test _ expression )
{
statement 1 ;
statement 2 ;
}
else
{
statement 3 ;
statement 4 ;
}s
//program which converts given years into seconds//
#include<iostream.h>
void main()
{
float years, seconds;
cout<<”Enter your age in years:”;
cin>>years;
if(years<0)
cout<<”Age cannot be negative=”<<endl;
else
{
seconds=years*365*24*60*60;
cout<<”you have lived for”<<seconds<<”seconds”;
}
}

- 28 -
Object Oriented Programming in C++ C.Md.Jamsheed

Nested if-else statements:


Multi-way decisions arise when there are multiple conditions and different actions to be taken
under each condition. A multi-way decision can be written by using if-else constructs in the
else-part as follows:
If(test-expression1)
Statement1;
Else
If(test-expression2)
Statement2;
Else
If(test-expression3)
Statement3;
Here , if test expression1 is true, the whole chain is terminated. Only if found false, the chain
of events continue. At any stage if an expression is true, the remaining chain will be
terminated.
//Usage of if ------else----if statement//
#include<iostream.h>
void main()
{
int age;
cout<<”Enter your age:”;
cin>>age;
if(age>12&&age<20)
cout<<”you are a teen-aged person:”;
else
if(age<13)
cout<<”you will surely reach teen-age”;
else
cout<<”you have crossed teen-age!”;
}

Switch statement:
The switch statement provides a clean way to dispatch to a different parts of a code based on
the value of a single variable or expression. It is a multi-way decision-making construct that
allows choosing of a statement or a group of statements among several alternatives. The switch
statement is mainly used to replace multiple if-else sequence which is hard-to-read and hard-to-
maintain.
Switch(option)
{
case1:cout<<”option #1 entered”;
break;
case2:cout<<”option #2 entered”;
break;
default:cout<<”Invalid option entered”;
}
The expression following the switch keyboard is an integer valued expression. The value of this
expression decides the sequence of statements begin with the keyboard case followed by a
constant integer. Control is transferred to the statements following the case. Label whose
constant is equal to the value of the expression in the switch srtatement. The default part is

- 29 -
Object Oriented Programming in C++ C.Md.Jamsheed

optional in the switch statement. The keyboard break is used to delimit the scope of the
statements under a particular case.
//Use of switch statement//
#include<iostream.h>
void main()
{
char ch;
cout<<”Enter the gender(m/f):”;
cin>>ch;
switch(ch)
{
case ‘m’:
cout<<”you are male:”;
break;
case ‘f’:
cout<<”you are female:”;
break;
default:cout<<”Invalid option:”;
}
}

(d)Goto statement:
The c++ language also provides the much abused goto statement for branching
unconditionally to any part of a program. A debate on whether the use of the goto construct in
structured programming is essential is not, is purely academic, but practically, the goto, is
never necessary and therefore is not used by many programmers. However, there are certain
places where the use of goto becomes mandatory. For instane, to exit from some deeply nested
loops, goto can be used. The general format of a goto statement is :
Goto label;
Here label is an identifier used to label the target statement to which the control should be
transferred. Control may be transferred to any other statement within the current function. The
target statement must be labeled and the label must be followed by a colon.
Label=statement;
//program using go to statement//
# include<iostream.h>
# include<conio.h>
void main()
{
int a, b;
cout<<”Enter a value”;
cin>>a;
if(a%2==0)
goto x;
else
goto y;
x=cout<<”a is even:”<<a;
goto z;
y=cout<<”a is odd:”<<a;
z:;
}

- 30 -
Object Oriented Programming in C++ C.Md.Jamsheed

Looping statements:
Loops cause a section of code to be executed repeatedly until a termination condition is met.
The following are the looping statements supported in c++:
(a) for statement
(b) while statement
(c) do-while statement

(a)For statement: The for loop is useful while executing a statement a fixed number of times.
Even here, more then on statement can be enclosed in curly braces to form a compound
statement.
For(initialization ;condition ; updation)
Statement;
On for(I=0;I<=n;I++)
Statement;
The for statement is a compact way to express a loop. All the four parts of a loop are in close
proximity with the for statement. The initialization part is executed only once. Next the test
condition is evaluated. It the test evaluates to false, then the next statement after the for loop is
executed. If he test expression evaluates to true, then after executing the body of the loop, the
update part is executed.
//program to calculated sum of first 15 even numbers and their squares//
# include<iosrteam.h>
void main()
{
int I;
int sum=0, sum-of-squares=0;
for (I=2;I<=30;I+=2)
{
sum+=I;
sum-of –squares+=I*I;
}
cout<<”sum of first 15 positive even numbers=”<<sum<<endl;
cout<<”sum of their squares=”<<sum-of-squares;
}
(b) While loop:
The while loop is used when the number of iterations to be performed are not known in
advance. The control flow in the while loop is as shown below. The statements in the loop are
executed if the test condition is true and the execution continues as long as it remains true.
While(expression)
{
_
_
}
statement;
Here the expression is a condition, if it is true then the loop will be executed else if the condition
is false the control will be transferred to the statement after the loop.
//program to find the average of marks using while loop//
# include<iostream.h>
void main()
{
int I, sum=0, count=0, marks;
cout<<”Enter marks, -1 at the end ---\n”;

- 31 -
Object Oriented Programming in C++ C.Md.Jamsheed

cin>>marks;
while(marks !=-1)
{
sum+=marks;
count++;
cin>>marks;
}
float average=sum/count;
cout<<”The average is =”<<average;
}
© Do---while loop”:
It is desirable to execute the body of a while loop at least once, even if the expression evaluates
to false during the first iteration. This requires testing of termination expression at 5the end of
the loop rather then the beginning as in while loop. So the do-while loop is called a bottom
tested loop. The loop is executed as long as the test condition remains true.
Do
{
---
---
}while (condition);
statement;
//program to dsisplay numbers 1-----------n using do-while //
# include<iostream.h>
void main()
{
int n;
cout<<”How many integers to be displayed:”;
cin>>n;
int I=0;
do
{
cout<<I<<endl;
I++;
} while (I<n);
}
Break statement:
A break construct terminates the execution of loop and the control is transferred tomthe
statement immediately following the loop. The term break refers to the act of breaking out of a
block code. We can use the break statement in for, while and do-while loop statements with
break statement.
For(init ; exp1 ; exp 2)
{
if (condition)
break;
} statement;

do
{
……….
If(condition)
Break;

- 32 -
Object Oriented Programming in C++ C.Md.Jamsheed

………
} while(condition);
statement;

while(expn)
{ ………
if(condition)
break;
………
}
statement;
continue statement :
The continue statement skips the remainder of the current iteration and initiates
the execution of the next iteration. When this statement is encountered in a loop, the rest of the
statement in the loop are skipped, and the control passes to the condition, which is evaluated,
and if true, the loop is entered again. The continue statement has the following syntax:
continue;
The continue statement can be used in for, while and do…….while loops.

For(init, expn1, expn2) while (expn) do


{ { ……….. {

if (expn) if (expn)
continue;
continue; ……….
…… }
}

// program to calculate sum of positive numbers//


#include<iostream.h>
void main()
{
int num,total=0;
do
{
cout<<” enter a number (0 to quit) “;
cin>>num;
if(num==0)
{
cout<<”end of data entry:”<<endl;
continue;
}
total+=num;
}
while(1)
cout<<” total of all +ve numbers is “ << total;
}

- 33 -
Object Oriented Programming in C++ C.Md.Jamsheed

ARRAYS AND STRINGS

DEFINITION OF ARRAY: An array is a group of logically related data items of the same data
type addressed by a common name and all the items are stored in contiguous (physically
adjacent) memory locations. For example, the statement.
Int marks[10];
Defines an arrays by the name marks that can hold a maximum of 10 elements. The individual
elements of an array are accessed and manipulated using the array name followed by their index.
The marks scored in the first subject is accessed by the marks[0] and the marks scored in the 10th
subject as marks[9]. In this case, a sequence of the integers representing the marks are stored
one after another in memory. The arrays can be used to represent a vector, matrix and three
dimensional arrays.

//program to calculate average age by using vector //


#include <iostream.h>
void main()
{
int age[5];
float sum=0;
for(int I=0;I<5;I++)
{
cout<<” enter person” << I+1<< “age”;
cin>>age[I];
}
for(I=0;I<5;I++)
sum+=age[I];
cout<< “average age = “ << sum/5;
}
like other normal variables, the array variable must be defined before its use. The syntax for
defining an array is as follows:

Examples: int marks[100];


Float salary[25];
Char name[50];
The maximum length of an array is upto 255 elements.

- 34 -
Object Oriented Programming in C++ C.Md.Jamsheed

Accessing arrays elements: Once an array variable is defined, its elements can be accessed by
using an index. The syntax for accessing array elements
Array name[index]
To access a particular element in the array, we have to specify the array name followed by an
integer constant or variable (array index) enclosed within square braces. The array index,
indicates the element of the array, which has to be accessed. For instance, the expression.
Age[4]
Access the 5th element of the array age. In the loop
For(int I=0;I<5;I++)
{
cout<<” enter person”<<I+1<<”age”;
cin>>age[I];
}
statements such as age[I]++; can be further and to increment or decrement (age[I]--). The
expression age[I] can also be represented as I[age]; similarly the expression age[3] is equivalent
to 3[age];
array initialization at definition: Arrays can be initialized at the point of their definition as
follows.
Data type array name[size]={list of values separated by comma};
For example, the statement
Int age[5]={19, 21, 16, 4, 50};

Defines an array of integers of size 5. in this case the first element of the array age is initialized
with 19, second with 21 and so on. A semicolon always follows closing brace. The array size
may be omitted when the array is initialized during array definition as follows.
Int age[]={19, 21, 16, 4, 50}
In such cases, the compiler assumes the array size to be equal to the number of elements
enclosed within the curly braces. The size of array is taken as 5
Int age[5]={19, 21, 16, 4, 50};
Or
Int age[]={19, 21, 16, 4, 50}

// program which finds the eldest & youngest person //


#include<iostream.h>
void main()
{
int I, n;
float age[25],younger, elder;
cout<<” how many persons are there in list:”;
cin>>n;
for(I=0;I<n;I++)
{
cout<<” enter person” <<I+1<<”age”;

- 35 -
Object Oriented Programming in C++ C.Md.Jamsheed

cin>>age[I];
}
younger=age[0];
elder=age[0];
for(I=1;I<n; I++)
{
if(age[I]<younger)
younger=age[I];
else
if(age[I]>elder)
elder=age[I];
}
cout<<” age of eldest person is “ <<elder<<endl;
cout<<” age of youngest person is “ << younger<<endl;
}

// program accepting 10 cells of array, print the given array in the reverse order in the original
order//
#include<iostream.h>
void main()
{
int a[10],I;
cout<<”enter 10 elements of array”;
for(I=0;I<=9;I++)
cin>>a[I];
cout<<”original array follows:”;
for(I=0; I<=9;I++)
cout<<a[I];
cout<<” reverse array follows:”;
for(I=9;I>=0;I++)
cout<<a[I];
cout<<” process over “ <<endl;
}
out put
enter 10 elements of array : 8 7 6 5 3 2 9 4 1 0
original array follows : 8 6 5 3 2 9 4 1 0
reverse array follows: 0 1 4 9 2 3 5 6 7 8

// accept an array of 10 cells, write a program to sort the elements//


#include<iostream.h>
void main()
{
int a[10], I, t=0,j;
cout<<” elements for the array:”;
for(I=0;I<=9;I++)
cin>>a[I];
cout<< “ unsorted array elements are:”;
for(I=0;I<=9;I++)
cout<<a[I];
for(I=0;I<9;I++)

- 36 -
Object Oriented Programming in C++ C.Md.Jamsheed

{
for(j=I+1;j<=9;j++)
if(a[I]>a[j])
{
t=a[I];
a[I]=a[j];
a[j]=t;
}
}
cout<<” sorted array follows:”;
for(I=\0;I<=9;I++)
cout<<” a[I]”;
}

- 37 -
Object Oriented Programming in C++ C.Md.Jamsheed

Unit-IV

Structures: Collection of logically related data items of different data types is known as
structures. It is also called as user defined data types. In c++ the keyword 'struct' is used for
defining the structure. The general syntax for structure definition is-

Struct tag name


{
Data type member-1;
Data type member-2;
-----------------;
-----------------;
Data type member-n;
} struct variable;

Here tag name gives the name of the structure member-1, member-2, -----, member-n
define between the opening and closing braces are members of a structure this is known as
template. The structure can be terminating with the help of a semicolon like other declarations.
The tag name or structure name is optional which can be used for creating structure variables
later in the programs. Structure members can be accessed with the help of dot operator using
structure variable.

Example:

Struct student
{
Int sno, m1, m2, m3, tot;
char sna[5],br[5];
} st;
Void main ()
{
cout<<"enter student rollno,name,branch,marks in three subjects";
cin>>st.sno>>st.sna>>st.br>>st.m1>>st.m2>>st.m3;
tot=m1+m2+m3;
cout<<"total marks of three subjects">>st.tot;
}

Array of structures: In order to store the information of more than one student array of
structure is used. Just like array variables structure variables can be defined as array of
structures, the syntax for defining the array of structures is-

Struct tag name


{
Data member-1;
Data member-2;
-------------;
-------------;
Data member-n;
} struct variable [size];
Example:

- 38 -
Object Oriented Programming in C++ C.Md.Jamsheed

Struct student
{
Int sno, date, month, year;
Char sna [8];
} st [5];
Void main ()
{
Int i;
For (i=0; i<=5; i++)
{
Cout<<"enter student rollno, name, date of birth";
Cin>>st[i].sno>>st[i].sna>>st[i].date>>st[i].month>>st[i].year;
}
For (i=0; i<=5; i++)
{
Cout<<"student rollno, name, date of birth";
Cout<<st[i].sno<<st[i].sna<<st[i].date"/"<<st[i].month"/"<<st[i].year;
}
Getch ();
}

Structures and functions: Structure variables can also be used as actual arguments for
providing the communications between he calling and called functions. When we use structure
variables as actual arguments for receiving the values in the function declarator we have to use
the same structure variable as actual argument. If the function definition returns structure data
type, you have to use the same data type for that function in function Prototype and in function
declarator. When we pass the structure variable as actual argument entire copy of the members
are transferred to the called function. The syntax for using functions with structures is-

Typedef (struct tag name dataype name)

Example: Use of structures and functions to demonstrate employee details.

#include<iostream.h>
#include<conio.h>
struct emp
{
int eno, bs;
char ena [10];
} e;
void main ()
{
cout<<"enter employee number, name, basic salary";
cin>>e.eno>>e.ena>>e.bs;
disp(e);
}
void disp (struct emp n)
{
cout<<n.eno<<n.ena<<n.bs;
}

- 39 -
Object Oriented Programming in C++ C.Md.Jamsheed

Unions: Union is another derived data type which can be used to store different data items just
like structure. Unions can be defined in c++ with the help of keyword 'union' and follows the
same syntax of structure definition. The general syntax of union definition is-

union tag name


{
data member 1;
data member 2;
-------------;
-------------;
data member n;
} union variable;

Union variables are created just like structure variables and accessing the members of the
union is also same as the structure. But there is one difference between structures and unions.
i.e., their storage representation.
In structures each member is having separate storage space, but in case of union only one
storage space is used for storing all the members that storage space is allocated by the compiler
based on the data types of the members. The member which requires highest storage space that
can be used for all the members in the union.

Example: Use of unions to demonstrate employee details

#include<iostream.h>
#include<conio.h>
union emp
{
int eno;
char ena [5];
float bs, hra, da, ta, ns;
} e;
void main ()
{
cout<<"enter eno, ena, bs";
cin>>e.eno>>e.ena>>e.bs;
e.hra=e.bs*0.3;
e.da=e.bs*0.4;
e.ta=e.bs*0.2;
e.ns=e.bs+e.hra+e.da+e.ta;
cout<<e.ns;
}

Class: A class is a collection of members and set of operations. This members are known as
instance variables or data members.the operations are known as methods or member functions.
In c++ classes are used for creating the user defined datatypes. The class definition is same as
the structure definition but there is a difference between structures and classes is that members
of structures are public by default whereas the members of the class are private by default. The
general syntax of class is-

- 40 -
Object Oriented Programming in C++ C.Md.Jamsheed

class class name


{
private:
data member 1;
data member 2;
-------------;
-------------;
data member n;
public:
member function 1( );
member function 2( );
-------------------;
-------------------;
member function n ( );
};

Object: Class definition declares only the structures of objects. It must be instantiated by
objects. Object is a runtime entity for providing the space and instantiating the class members.
Objects are created in c++ like structure variables. The general syntax for crating object is-

class classname object 1, object 2, -----object n;

The keyword 'class' is optional for creating the objects. Once an object of a class has
been created it is possible to access the members with the help of objects. Members are accessed
by using the dot (.) operator. The syntax for accessing member of a class is-
Objectname.data members;

Defining the member functions: The data members of a class must be declared with in the
class where as the member functions can be defined inside the class or outside the class. The
syntax for a member function definition changes depending on whether it is defined inside or
outside the class.

Member function inside the class: The syntax for specifying a member function declaration is
similar to the normal function definition except that it is enclosed with in the body of the class.
All the member function defined within the body of the class are treated as inline by default,
except those member having looping statements such as for, while etc. Member functions can be
accessed by the objects of the class with the dot (.) operator. A member function of a class can
also be accessed without using objects. i.e., it can be accessed with the help of another member
function of its own class. This type of accessing a member function by another member function
of its own class knows n as nesting of member functions.

Example: Use of member function inside the class body to demonstrate details of a employee.

#include<iostream.h>
#include<conio.h>
class person
{
char ena[10],job [10];
int age,sal;
public:

- 41 -
Object Oriented Programming in C++ C.Md.Jamsheed

void getdata()
{
cout<<"enter employee name, job, age and salary";
cin>>ena>>job>>age>>sal;
}
void displaydata()
{
cout<<"employee name :"<<ena<<endl;
cout<<"job :"<< job<<endl;
cout<<"age :"<< age<<endl;
cout<<"Sal :"<< sal;
}
};
void main()
{
person p;
p.getdata ();
p.displaydata ();
}
Member functions outside the class: For defining the member functions outside the class is the
member function prototype is declared within the class. Whenever the member function is
defined outside the class specification, the user requires a special operator. i.e., scope resolution
operator (::). This operator can be used for identifying eh member functions of particular class.
The syntax for defining the member function outside the class specification is-

return type classname::function name (formal arguments)


{
body of function;
};

Example: Use of member function outside the class body to demonstrate details of a employee.

#include<iostream.h>
#include<conio.h>
class person
{
char ena[10],job [10];
int age,sal;
public:
void getdata();
void displaydata();
};
void person::getdata()
{
cout<<"enter employee name, job, age and salary";
cin>>ena>>job>>age>>sal;
}
void person::displaydata()
{
cout<<"employee name :"<<ena<<endl;

- 42 -
Object Oriented Programming in C++ C.Md.Jamsheed

cout<<"job :"<< job<<endl;


cout<<"age :"<< age<<endl;
cout<<"Sal :"<< sal;
}
void main()
{
person p;
p.getdata ();
p.displaydata ();
}

Data hiding: One of the most important features of object oriented programming language is
provide security to the data items that means hiding the data items from external interferences.
In c++ it can be achieved with the help of classes that means class contains data members and
member functions. At the time of declaring the data items and member functions, you have to
specify anyone of the access modifiers that are available in c++ for the members and member
functions.
C++ provides three different types of access modifiers. They are - 1) private
2) Public and 3) protected.

Private: Once we declare members of a class as private they have strict access control. Only the
member functions of the same class can access there members and they cannot accessed by any
other function declared outside the class. Here private access modifier provides the mechanism
for preventing accidental modifications of the data members.

Example: Use of access modifier to demonstrate private members of a class.

#include<iostream.h>
#include<conio.h>
class example
{
private:
int a,b;
public:
void getdata();
void displaydata();
};
void example::getdata()
{
cout<<"enter the values of a,b";
cin>>a>>b;
}
void example::displaydata()
{
cout<<a<<b;
}
void main()
{
example e;
e.getdata ();
e.displaydata ();

- 43 -
Object Oriented Programming in C++ C.Md.Jamsheed

In the above example data members a, b are treated as private. These two members can
be acessed by the function getdata () and putdata (), because that functions belongs to the same
class.

Public: The members of a class which are to be accessible by member functions belong to that
program. i.e., the member function may be existing within the class or it may exist any other
classes in a program. Here these data members can be accessed without any restriction from any
where in the program. All the data members of public access modifier can be treated as a global
data like other programming languages. Therefore this access modifier can't provide security to
the data items.

Example: Use of access modifier to demonstrate public members of a class.

#include<iostream.h>
#include<conio.h>
class example
{
public:
int a,b;
public:
void getdata();
void displaydata();
};
void example::getdata()
{
cout<<"enter the values of a,b";
cin>>a>>b;
}
void example::displaydata()
{
cout<<a<<b;
}
void main()
{
example e;
e.getdata ();
e.displaydata ();
}

Protected: It is similar to the private but their is one significant difference between private and
protected in the concept of inheritance. private access modifier can't allows the user for
accessing the data members by using the member functions which are not belongs to same class
and this modifier doesn't allows for accessing the data members by functions even they belongs
to derived that is why instead of using private access modifiers for the data member protect is
used when we are applying the concept of inheritance. The protected data members can be
accessed by member functions belongs to the same class and also belongs to the derived class.

Example: Use of access modifier to demonstrate protected members of a class.

- 44 -
Object Oriented Programming in C++ C.Md.Jamsheed

#include<iostream.h>
#include<conio.h>
class marks
{
protected:
int a, b;
public:
void getdata()
{
cout<<"enter values of a, b";
cin>>a>>b;
}
void putdata()
{
cout<<"value of a and b is"<<a<<b;
}
};
class result: public marks
{
int tot;
public: void display();
}
};
void result::display()
{
tot=a+b;
}
void main()
{
result r;
r.display();
}

Passing objects as arguments: Like other functions the member functions allows variables as
actual arguments. Instead of variable in c++ programming language objects can be used as
actual arguments. For passing objects as actual arguments we are having three parameter
passing techniques, they are-
1) Pass by value
2) Pass by address
3) Pass by reference

These three techniques are implemented in same manner while passing variables as an
actual arguments for providing the line between the calling and called function. Whenever
objects are used as an actual parameter at the time time of receiving the formal parameter must
be declared of abstract data type. The object carries the entire information belongs to class
between the member functions.
The member functions returns objects to this calling function. Whenever a member
function return objects the return type of that function is declared as the return object type.

Example: Use of passing objects by using pass by value mechanism to demonstrate the distance
calculation.

- 45 -
Object Oriented Programming in C++ C.Md.Jamsheed

class distance
{
float feet, inches;
public:
void input (float fe, float in)
{
feet=fe;
inches=in;
}
void read ()
{
cout<<"enter feet's and inches values";
cin>>feet>>inches;
}
void show ()
{
cout<<feet<<inches;
}
void add (distance d1, distance d2)
feet=d1.feet+d2.feet;
inches=d1.inches+d2.inches;
if (inches>=12.0)
{
feet=feet+1;
inches=inches-12.0;
}
};
void main ()
{
distance d1, d2, d3;
d1.input (11.5, 6.0);
d2.read ();
cout<<d1.show ();
cout<<d2.show ();
d3.add (d1, d2);
cout<<d3.show ();
}

Example: Use of passing objects by pass by reference mechanism to demonstrate transfer of


money from one account to other.

class account
{
int accno;
float bal;
public:
void get data ()
{
cout<<"enter account number, balance";
cin>>accno>.bal;

- 46 -
Object Oriented Programming in C++ C.Md.Jamsheed

}
void setdata (int accin)
{
accno=accin;
bal=0;
}
void setdata (int accin, float bal)
{
accno=accin;
balance=bal;
}
void display ()
{
cout<<"account no :"<< accno<<"and balance :"<< bal;
}
void moneytransfer (account &acc, float amt)
};
void account::moneytransfer (account &acc, float amt)
{
bal=bal-amt;
acc.bal=acc.balance+amt;
}
void main ()
{
int transmoney;
account acc1, ac2, acc3;
acc1.getdata ();
acc2.setdata (10);
acc3.setdata (20, 1000.00);
acc1.display ();
acc2.display ();
ac3.display ();
cout<<"how much amount transfer from ac3 to acc1";
cin>>transmoney;
ac3.moneytransfer (ac1, transmoney)
ac1.display ();
acc2.display ();
ac3.display ();
}

Friend function: The concept of encapsulation and data hiding dictate that non member
functions should not be allowed to access private and protected members. Some times it leads to
t he inconvenience for designing programs. i.e., the use wants a function to operate on objects of
two different classes. It requires allowing functions outside a class and manipulating the private
members of the class. This can be achieved in c++ by using the concept of friends.
In c++ friend functions can be identified with the help of the keyword 'friend', at the time
of writing code for the function, there is no need to use keyword 'friend' once
again.The general syntax for declaring a friend function is-

Firend functionname ( );

- 47 -
Object Oriented Programming in C++ C.Md.Jamsheed

Example: Use of friend function to demonstrate sum of two numbers.

#include<iostream.h>
#include<conio.h>
class one
{
int num1,num2;
public:
void setdata (int.in1, int.in2)
{
cin>>in1>>in2;
num1=in1;
num2=in2;
}
friend class two;
class two
{
Public:
{
return (b1.num1+b1.num2)
}
};
void main ()
{
int m, n;
one b1;
two b2;
b.setdata (300,500);
cout<<"sum :"<< b1.sum (b1);
}
The friend functions allow to access private and protected data members of a particular
class. A friend function possesses the following special characteristics.
1) The scope of a friend function is not limited to the class in which it has been declared as a
friend.
2) A friend function can be declared either in the private part or public part of the class without
effecting its meaning.
3) While considering the friendship between the classes the user must know the following-
a) Friendship is not mutually by default. i.e., once 'B' is declared as a friend of ‘A’ 'B’
doesn't give 'A’ the right to access the private members of the class.
b) Friendship when applied to the program design is an escape mechanism which
violates the rule of data hiding. Therefore usage of friend classes should be limited those classes
where it is absolutely essential.

Constructors: A constructor is a special member function. The main purpose of constructors in


c++ is to allocate the required resources such as memory and initialize the objects of its class.
A constructor is distinct from other member functions of the class. i.e., it has the same
name as its class name. The constructor is the first member function executes automatically
when an object is created to that class. The general syntax for defining constructor is-

- 48 -
Object Oriented Programming in C++ C.Md.Jamsheed

class classname
{
data members;
public:
class name() // constructor
{
--------;
--------;
}
};

A constructor has the following characteristics –


1) It has the same name as that of the class to which it belongs.
2) It is executed automatically whenever the class is instantiated.
3) It doesn’t have any return type not even void.
4) It is normally used to initialize the data member of a class.
5) It is also used to allocate the resources such as memory to the data members of a class.

Constructors are basically classified in to three types-


1. Default constructor
2. Parameterized constructor
3. Copy constructor

when a constructor doesn’t have to accept arguments, it is called an object’s default


constructor. Like member functions, it is possible to pass the arguments to the constructors. The
arguments list can be specified with in the braces similar to the argument list in the member
functions. Constructors with arguments are called as parameterized constructors.

Default constructors:

Example: Use of default constructors to demonstrate the febinocci series.

#include<iostream.h>
#include<conio.h>
class febinocci
{
private:
int f0,f1,fib,
public:
febinocci();
{
f0=0;
f1=1;
fib=f0+f1;
}
void logic()
{
f0=f1;
f1=fib;
fib=f0+f1;

- 49 -
Object Oriented Programming in C++ C.Md.Jamsheed

}
void display()
{
cout<<fib;
}
void main()
{
febinocci f;
flogic();
f.dislplay();
}

Parameterized constructor:

Example: Use of parameterized constructors to display two numbers.

#include<iostream.h>
#include<conio.h>
class numbers
{
private:
int m,n;
public:
numbers(int,int);
}
};
numbers :: numbers(int x, inty)
{
m=x;
n=y;
}
void main()
{
numbers n;
n(0,100);
}

Copy constructors: In c++ it is possible to pass the different types of arguments to the
constructor’s member functions except an object of its own class. Whenever the user tries to
pass the object of the class as a parameter to that constructor of the same class is illegal as
shown below.

Class ex
{
------;
------;
ex (ex obj); // illegal declaration
};

- 50 -
Object Oriented Programming in C++ C.Md.Jamsheed

Instead of passing value of object as parameter to the constructors we can pass the
reference of the object to the constructor member function. When a constructor having a
reference of an object as an argument is known as copy constructor.

The compiler copies all the members of the user defined source object to the destination
object in the assignment statement. When its members are statistically allocated. The main
purpose of copy constructor is the values of a particular object is to be copied into another
object.

Example: Use of copy constructor to add two complex numbers.

#include<iostream.h>
#include<conio.h>
class code
{
int id;
public:
code()
{
}
code(int a)
{
id=a;
}
code(code &x)
{
id=x.id;
}
void display()
cout<<id;
}
};
void main()
{
code a(100);
code b(a);
code c=a;
code d;
d=a;
a.display();
b.display();
c.display();
d.display();
}

Constructor overloading: In c++ programming we may use number of constructors for a class.
i.e., just like function overloading, constructors are overloaded whenever a class having multiple
constructors that feature is known as constructor overloading. i.e., all the constructors have the
same name of its class name and they differ only in terms of their number of arguments, data
types of arguments or both. Depending upon the arguments the particular constructor definition
is executed.

- 51 -
Object Oriented Programming in C++ C.Md.Jamsheed

Example: Use of constructor overloading to demonstrate sum of complex numbers.

#include<iostream.h>
#include<conio.h>
class complex
{
float real,image;
public:
complex() // default constructor
{
real=image=0.0;
}
complex (float readin, float imagein) // parameterized constructor
{
realin=realin;
image=imagein;
}
void show(char *mesg)
{
cout<<msg<<real;
if(iamge<0)
cout<<”-i”;
else
cout<<”-i”;
}
complex add(complex c2)
};
complex complex::add(complex(c2)
{
complex.temp;
temp.real=rel+c2.real;
temp.image=image+c2.image;
return(temp);
}
void main()
{
complex .c3;
complex c1(2.5,3.5);
complex c2(5.5);
c1.show(“c1=”);
c2.show(“c2=”);
c3.c1.add(c2);
c1.show(“c3=”);
}

Destructor: Destructor us also a special member function available in c++ programming


language. When the user wants to destroy object the destructor can be used. It is invoked
automatically when an object is destroyed, i.e., when the control leaves from that object thee
definition of destructor is executed. It has the same name of the class in which it is declared and
this can be identified b using a special character tild(~) followed by the name of th its class

- 52 -
Object Oriented Programming in C++ C.Md.Jamsheed

(destructor). It is invoked automatically to reclaim all the resources allocated to the object when
the object goes out of scope and that is no longer needed for our program. The general syntax
for defining destructors is-

class classname
{
data members;
public:
~class name() // destructor
{
--------;
--------;
}
};

The following are some important characteristics of destructors-


1) The destructor function has the same name as the class but prefixed by a character “~’ which
can be used to distinguish the constructor of the same class.
2) Unlike the constructor, the destructor doesn’t take any arguments, because there is only one
way
3) The destructor doesn’t have any return value.
4) Like constructors it doesn’t have any return type.
5) There can be only one destructor in each class.

Example: Use of destructors to demonstrate addition of two numbers.

#inlcude<iostream.h>
#inlcude<conio.h>
class first
{
private:
int a,b;
public:
first()
{
a=0;
b=0;
}
first(int x,int y)
{
a=x;
b=y;
}
void display()
{
int sum;
sum=a+b;
cout<<”sum of two numbers”<<sum;
}

- 53 -
Object Oriented Programming in C++ C.Md.Jamsheed

~first()
{
cout<<”object deleted”;
}
};
void main()
{
first f(50,100);
f.display();
}

Inheritance: Reusability is another important feature of object oriented programming language.


C++ programming language supports reusability with the help of inheritance property. This is
basically done by creating new classes reusing the properties of the existing classes. The
mechanism of deriving a new class from an old one is called inheritance. The old class is
referred as base class or parent class or super class and the new class is referred as derived class
or child class or sub class.
The derived class inherits some or all the properties from the base class. The general
syntax of derived class is-

class derived classname : [access modifier] base class name


{
--------;
--------;
};

Here class is a user defined data type and derived class name and base class name are
two identifier names. The colon (:) indicates that the derived classname is derived from the base
class name. Access modifier is optional, it may be either private or public. The default access
modifier is private. The access modifier specifies tha the features of the base class are privately
inherited or publicly inherited.

When a baseclas is privately inherited bya drived class public members of base calss become
privatge members of the derived class. Therefore the public members of the base class can be
accessed by the member function of derived class. On the other hand baseclass is publicly
inherited by a derived class, public members of the base cals mbecomes public members of
drived class. Therefore they are accessible to the objects of drived class. In both cases the
private members of base class are not inherited and therefore the private members of bse class
will never become the members of the derived class.

Forms of inheritance: The derived class inherits some of the features of the baseclass
depending upn the visibility mode and level of mode. A derived class canb e inherited in any
one of the form-
1) Single inheritance
2) Multiple inheritance
3) Hybrid inheritance
4) Multi level inheritance
5) Multipath inheritance
6) Hierachial inheritance.

Single Inheritance: A subclass is derived from one base class is called single inheritance.

- 54 -
Object Oriented Programming in C++ C.Md.Jamsheed

Base class - A

Derived class - B

The subclass ‘B’ inherits the properties of base class ‘A’. Here the subclass or child class
‘B’ is represented as derived class and the class parent ‘A’ is known as base class or super class.
The child class has two parts one is derived part and other is incremental part. The incremental
part is the new code written specifically for the child class. The above figure states the examples
of the child and parent class.

Example: Use of single inheritance to display the basic and physical details of a student.

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class basicinfo
{
private:
char name[20],gen;
int rno;
public:
void getdata();
void putdata();
};
class physicalfit:public basicinfo
{
private:
float ht,wt;
public:
void getdata();
void putdata();
};
void basicinfo::getdata()
{
cout<<”enter name,rno,gen”<<endl;
cin>>name>>rno>>gen;
}
void basicinfo::putdata()
{
cout<<”the students information is”<<endl;
cout<<name<<rno<<gen;
}
void physicalfit::getdata()
{
basicinfo::getdata();
cpit<<”enter height and weight”<<endl;
cin>>ht>>wt;
}
void physicalfit::putdata()

- 55 -
Object Oriented Programming in C++ C.Md.Jamsheed

{
basicinfo::display();
cout<<ht<<wt;
}
void main()
{
physicalfit D[10];
int n;
cout<<”enter how many students”<<endl;
cin>>n;
cout<<”enter the follwing information”<<endl;
for(i=0;i<=n-1;i++)
{
D[i].getdata();
}
cout<<”Students information”<<endl;
for(i=0;i<=n-1;i++)
{
D[i].putdata();
}
}
Multiple Inheritance: A subclass is derived from more than one two or more super classes is
known as multiple inheritance.

Base classes -
A B

Child class -
C

Here the child class ‘C’ can acquire the properties of two base classes i.e., class ‘A’ and
class ‘B’ and its own properties. In multiple inheritance the child class can inherits the
properties of more than one base class. For example the child inherits the attributes of father and
mother resperctively.

Example: Use of multiple inheritance to display the multiplication of two numbers.

#include<iostream.h>
#include<conio.h>
class one
{
protected:
int m;
public:
void getdata();
};
class two
{
protected:
int n;

- 56 -
Object Oriented Programming in C++ C.Md.Jamsheed

public:
void inputdata();
};
class three:public one, public two
{
public:
void putdata();
};
void one::getdata()
{
cin>>m;
}
void two::inputdata()
{
cin>>n;
}
void three::putdata()
{
cout<<m*n;
}
void main()
{
three t;
t.getdata();
t.inputdata();
t.putdata();
}

Hierarchical Inheritance: Number of subclasses are derived from only one superclass is
known as hierarchical inheritance.

Base class -
A

Child classes -

B C D

Here the sub classes ‘B’,’C’,’D’ can inherits the properties of class ‘A’ which is parent
class or base class. The derived class has its own code as well as the code inherited from base
class. For example the base class vehicle is having subclasses ‘light motor’ and ‘heavy motor’.
In term the light motor class having its own sub classes ‘gear motor’ and ‘non gear motor’ and
the heavy motor class having the subclasses ‘passengers’ and goods.

Example: Use of hierachial inheritance to display the details of the vehicle.

#include<iostream.h>
#include<conio.h>
const maxlen=25;
class vehicle
{

- 57 -
Object Oriented Programming in C++ C.Md.Jamsheed

protected:
char name[maxlen];
int wheelscount;
public:
void getdata()
{
cout<<"name of the vehicle";
cin>>name>>wheelscount;
}
void displaydata()
{
cout<<"name of the vehicle"<<name;
cout<<"wheels"<<wheelscount;
}
};
class lightmotor:public vehicle
{
protected:
int speedlimit;
public:
void getdata()
{
vehicle::getdata();
cout<<"enter speed limit";
cin>>speedlimit;
}
void displaydata()
{
vehicle::displaydata();
cout<<speedlimit;
}
};
class heavymotor:public vehicle
{
protected:
int loadcapacity;
char permit[maxlen];
public:
void getdata()
{
vehicle::getdata();
cout<<"enter load capacity";
cin>>loadcapacity;
cout<<"enter permit type";
cin>>permit;
}
void displaydata()
{
vehicle::displaydata();
cout<<"enter load carrying capacity";
cin>>permit;

- 58 -
Object Oriented Programming in C++ C.Md.Jamsheed

}
};
class gearmotor:public lightmotor
{
protected:
int gearcount;
public:
void getdata()
{
lightmotor::getdata();
cout<<"enter no of gears";
cin>>gearcount;
}
void displaydata()
{
lightmotor::displaydata();
cout<<gearcount;
}
};
class nongearmotor:public lightmotor
{
public:void getdata()
{
lightmotor::getdata();
}
void displaydata()
{
lightmotor::displaydata();
}
};
class passenger:public heavymotor
{
protected:
int sitting,standing;
public:
void getdata()
{
heavymotor::getdata();
cout<<"enter maximum seats";
cin>>sitting;
cout<<"enter maximum standing availability";
cin>>standing;
}
void displaydata()
{
heavymotor::displaydata();
cout<<sitting;
cout<<standing;
}
};
class goods:public heavymotor

- 59 -
Object Oriented Programming in C++ C.Md.Jamsheed

{
public:void getdata()
{
heavymotor::getdata();
}
void dispaydata()
{
heavymotor::displaydata();
}
};
void main()
{
gearmotor v1;
passenger v2;
cout<<"enter data for gearmotor vehicle";
v1.getdata();
cout<<"enter data for passendger motor vehicle";
v2.getdata();
cout<<"Data of gearmotor vehicle";
v1.displaydata();
cout<<"Data of passenger motor vehicle";
v2.displaydata();
}

Multilevel Inheritance: A subclass is derived from another subclass is known as multilevel


inheritance.

Base class - A

Intermediate B C
Base class -

Child class - D E F

Here the subclasses ‘B’ and ‘C’ inherits the properties of ‘A’ which is base class. The
derived class ‘D’, ‘E’ inherits the properties of derived class ‘B’. The derived class ‘F’ inherits
the properties of derived class ‘C’ which interm acts as base class for the derived class ‘F’.

Example: Use of multilevel inheritance to demonstrate the details of a product.

#include<iostream.h>
#include<conio.h>
class product
{
int pno;
char pname[10];
public:
void getdata()

- 60 -
Object Oriented Programming in C++ C.Md.Jamsheed

{
cout<<"enter product number and name";
cin>>pno>>pname;
}
void putdata()
{
cout<<pno<<pname;
}
};

class item:public product


{
private:
int stock;
public:
void getdata()
{
product::getdata();
cout<<"enter stock";
cin>>stock;
}
void putdata()
{
product::putdata();
cout<<stock;
}
};
class price:public item
{
private:
float rate;
public:
void getdata()
{
item::getdata();
cout<<"enter price";
cin>>rate;
}
void putdata()
{
item::putdata();
cout<<rate;
}
};
void main()
{
price p;
cout<<"enter products information";
p.getdata();
cout<<"products information";
p.putdata();

- 61 -
Object Oriented Programming in C++ C.Md.Jamsheed

Hybrid Inheritance: Derivation of a class involving more than one form of inheritance is called
hybrid inheritance.

Base class - A

sIntermediate B C
base class -

Child class - D

The hybrid inheritance is the combination of multilevel and multiple inheritances. Here
the subclass ‘D’ can inherit the properties of base class ‘C’ and the properties of derived class
‘B’ which is interm derived from base class ‘A’. Here the sub class ‘D’ inherits the properties of
two different classes.

Example: Use of hybrid inheritance to demonstrate student details.

#include<iostream.h>
#include<conio.h>
class student
{
protected:
int rno;
public:
void getdata()
{
cout<<"enter rollno";
cin>>rno;
}
void putdata()
{
cout<<rno;
}
};
class marks:public student
{
protected:
int m1,m2;
public:
void getdata()
{
student::getdata();
cout<<"enter marks in two subjects";
cin>>m1>>m2;
}
void putdata()
{
student::putdata();

- 62 -
Object Oriented Programming in C++ C.Md.Jamsheed

cout<<m1<<m2;
}
};
class sports
{
protected:
int score;
public:
void getdata()
{
cout<<"enter score";
cin>>score;
}
void putdata()
{
cout<<score;
}
};
class result:public marks, public sports
{
protected:
int tot;
public:
void getdata()
{
marks::getdata();
sports::getdata();
}
void putdata()
{
marks::putdata();
sports::putdata();
tot=m1+m2+score; cout<<tot;
}
};
void main()
{
result r;
r.getdata();
r.putdata();
}

Multipath Inheritance: Derivation of a class from other derived classes which are derived from
the same base class is called multipath inheritance. It is also referred as virtual base class.

Base class - A

Intermediate B C
base class -

Child class - D

- 63 -
Object Oriented Programming in C++ C.Md.Jamsheed

In multipath inheritance the three kinds of inheritance namely multilevel, multiple and
hierarchical inheritance are involved. The child class ‘D’ has two direct base classes ‘B’ and ‘C’
which themselves have a common base class ‘A’. The class ‘D’ inherits the traits of class ‘A’
via two separate paths. It can also inherit directly as shown above by the broken line. The class
‘A’ is sometimes referred to as indirect base class. The class ‘D’ inherits the features of ‘B’ and
‘C’ class which means that the class ‘D’ has duplicate sets of the members from class ‘A’ which
introduces ambiguity (confusion/doubt). To avoid these problem base class can be declared as
virtual base class while declaring the intermediate base class.

Example:

#include<iostream.h>
#include<conio.h>
class student
{
protected:
int rno;
public:
void getdata()
{
cout<<"enter rollno";
cin>>rno;
}
void putdata()
{
cout<<rno;
}
};
class test:virtual public student
{
protected:
float m1,m2;
public:
void getdata()
{
student::getdata();
cout<<"enter marks of two subjects";
cin>>m1>>m2;
}
void putdata()
{
student::putdata();
cout<<m1<<m2;
}
};
class sports:virtual public student
{
protected:
float score;
public:

- 64 -
Object Oriented Programming in C++ C.Md.Jamsheed

void getdata()
{
student::getdata();
cout<<"enter score";
cin>>score;
}
void putdata()
{
student::putdata();
cout<<score;
}
};
class result:public test, public sports
{
protected:
float tot;
public:
void getdata()
{
test::getdata();
sports::getdata();
}
void putdata()
{
test::getdata();
sports::getdata();
tot=m1+m2+score;
cout<<tot;
}
};
void main()
{
result r;
r. getdata();
r.putdata();
}

- 65 -

You might also like