DR - Jyothirmayi Degree College, Adoni.: Paper-III - Object Oriented Programming Using C++: Unit-1 Fundamentals
DR - Jyothirmayi Degree College, Adoni.: Paper-III - Object Oriented Programming Using C++: Unit-1 Fundamentals
Jamsheed
-1-
Object Oriented Programming in C++ C.Md.Jamsheed
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.
-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.
-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).
-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);
-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
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 .
-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
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.
- 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.
- 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.
The I/O stream facility of C++ provides an easy means to perform I/O.
- 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:
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.
- 13 -
Object Oriented Programming in C++ C.Md.Jamsheed
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;
- 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.
#include<iostream.h>
void main()
{
int a, b;
int c=20;
float d;
a=c;
b= c+20;
d= 20.5;
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.
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.
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 : ‘ 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.
- 17 -
Object Oriented Programming in C++ C.Md.Jamsheed
{
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
- 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.
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
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
- 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
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 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.
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;
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
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.
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
( 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
( 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
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
- 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.
( 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 ;
}
- 28 -
Object Oriented Programming in C++ C.Md.Jamsheed
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.
if (expn) if (expn)
continue;
continue; ……….
…… }
}
- 33 -
Object Oriented Programming in C++ C.Md.Jamsheed
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.
- 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}
- 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
- 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-
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-
- 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-
#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 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.
#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
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-
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-
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
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.
#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.
#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.
- 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 ();
}
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
#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.
- 48 -
Object Oriented Programming in C++ C.Md.Jamsheed
class classname
{
data members;
public:
class name() // constructor
{
--------;
--------;
}
};
Default constructors:
#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:
#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.
#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
#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=”);
}
- 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
{
--------;
--------;
}
};
#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();
}
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.
#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.
#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();
}
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’.
#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;
}
};
- 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.
#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 -