Object Oriented Programming Through C++
Object Oriented Programming Through C++
CHAPTER – 1
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING (OOP)
INTRODUCTION
What is “C++”?
C++ is an object oriented programming language. In other words we can say that it is a Hybrid (All features of “C” can be directly
implemented with “C++”) programming language or it is superset of “C”.
What is the difference between “C” and “C++”?
Point “C” Language “C++” Language
Input/Output Through Library function Through stream (Object)
BASIC CONCEPTS OF OOPs
Object oriented programming language have developed in an evolutionary manner and have become very popular over
past few year. C++ is one such language. It is necessary to understand some of the concept of used extensively in OOP. These
include:
1. Object 2. Classes 3. Inheritance 4. Encapsulation
ADVANTAGE of OOP
OOP offers several benefits to the program designer and the user.
• Through inheritance, we can eliminate redundant code and extend the use of existing classes.
• The principle of data hiding helps the programmer to build secure programs that cannot be invaded by code in other parts of the
program.
• It is possible to have multiple instances of an object to co-exist without any interference.
• It is easy to partition the work in a project based on objects.
• It is possible to map objects in the problem domain to those in the program.
• Software complexity can be easily managed.
COMPARISION OF PROCEDURAL PROGRAMMING AND OOPs
When we need to read data item in an object, we call a member functions in the object. The function will access data and
return us the value. we cannot access data directly, because data is hidden and cannot be altered accidentally. Data and its
functions are said to be encapsulated into a single entity.
When we need to modify the data in an object, we need to know the functions that interact with it. Thus we use that
function. This procedure simplifies in writing, debugging and maintaining a program. A C++ program thus consists of number of
objects which communicate with each other by calling one another’s member functions.
DEFINITION OF CLASS AND OBJECT
Class: - The concept of class is best understood with an analogy. Class is the way to define/declare the attribute (Instance
Variable) and functionality of an object.
Object: - An object is the something that has a fixed shape or well defined boundary. In the ordinary sense, an Object is
something which is capable of being seen. A object can be any one or all of the following:
(a) A visible thing
(b) Something that can be picked up by a person
(c) Something towards which thought or action is directed
CONCEPT OF INHERITANCE AND ENCAPSULATION
Inheritance:-This feature of c++, supports re-usability means that existing class/old class can be extended by a new class. New
class is called derived class and old class, on which a new class is created, is called base class.
Encapsulation: - It is mechanism that associates the code and the data it manipulates into a single unit and keeps them safe from
external interference and misuse. In c++, this is supported by a construct called class. An instance of class is known as an object,
which represents a real word entity.
OPERATOR OVERLOADING
‘C++’ provides feature to overload mostly arithmetic, relational and other operators. Overloaded means operator can be
used in c++ program for addition work not existing task. For example existing function of – (minus) is to negate the digit. But we
can use this operator to negate an object (i.e. the additional task of minus operator).
Statements to perform additional task, are written under special function namely operator ( ), i.e. provided by c++.
Syntax to use operator function: -
Return type operator <operator sign> (argument)
{ }
DYNAMIC BINDING
It means that the code links with program call is not known until the time of call at run time. Dynamic link libraries include
predefined functions that are linked with application program when it is loaded dynamically, instead of when executable file is
generated statically. It is also known as late binding.
BASIC PROGRAM CONSTRUCTION
#iinclude <iostream.h> int x,y,z; z=x+y;
void main() cout<<” enter two integer no.”; cout<<” total is :”<< z<< endl;
{ cin>>x>>y; }
Program statements: - C++ has the following types of program statement:
NOTES BY –BALJEET SINGH SINWAR
28
OBJECT ORIENTED PROGRAMMING THROUGH C++
(i) Declaration statement (ii) Assignment statement (iii) Function call statement (iv) Return statement
Comments – Comments can be included in a program in three different ways in C++ as given below:
Type Usages
/* */ All characters between /* and */ are ignored.
// All characters after the // up to end of the line are ignored.
CHAPTER – 2
ELEMENTS OF C++ LANGUAGE
TOKENS & IDENTIFIERS
Tokens – Token is the smallest element of a program that is meaningful to the compiler. When we submit a java program to the
java compiler, the compiler goes through the text and extracts individual tokens. Tokens can be categorized into the following five
types:
(a) Identifier (b) Keywords (c) Constants (d) Strings (e) Operators
(a) Identifiers: – Identifiers refer to the names of variables, functions, arrays etc. given by a programmer. These are also the
names of language objects, which can take many values, one at time. A variable is a name that the program associates with a
storage location in memory.
The following are the rule to name a Identifier:-
It can consist of any sequence of letter, digits and underscore (_).The first character should be a letter or an underscore.
No other special characters are allowed. Reserved words (Keyword) cannot be used as name of
identifier.
It is case sensitive language, so
(b) Keywords – The words which are reserved to do specific tasks at time of designing a programming language is known as
Keywords. Following are the keywords:
auto double int continue for virtual struct
break else long default goto catch switch
case enum register do if private typedef
char extern return asm new try union
const float short operator this inline unsigned
template static signed throw delete volatile void
protected class sizeof friend public while
Character set: - There are two character sets in c++ language. These are
(a) Source characters: - Using source characters, the source text is created. Example - Alphabets A to Z and _(underscore),
Decimals 0 to 9, Special characters + - * ~ # % etc.
(b) Execution characters/escape sequences: - These are interpreted at time of execution. The value of execution characters are
defined as per the implementation. C++ provides the mechanism to get such characters that are invisible or difficult
through execution characters. Execution characters and escape sequences are used inter-changeably. Following are the
execution characters:
Execution Character Meaning Result at execution time
\0 End of string Null
\n End of a line Moves the active position to the initial position of the next line.
\r Carriage return Moves the active position to the initial position of the next paragraph.
\f Form feed Moves the active position to the initial position of the next logical page.
\v Vertical tab Moves the active position to the next vertical tabulation position.
\t Horizontal tab Moves the active position to the next horizontal tabulation position.
\b Backspace Moves the active position to the previous position on the current line.
\a Alert Produces an audible alert
\\ backslash Presents with a backslash \.
VARIABLES AND CONSTANTS
Variable: - A variable is a name that our program associated with a storage location in memory. After declaring a variable within a
program we can assign it a value.
(b) Constants – Constants are refer to fixed values that do not change during the execution of a program.
Constants are the following types: -
(i) Backslash character constant: - The backslash (\) alters the meaning of the character that follows it. Following are the
backslash character string and their meanings:
(ii) Numeric constant : - It has a constant numeric value assigned to it. The value of the constant can be positive or negative
numeral. There are two types of numeric constant:
Integer Constant: - Integers constant are whole numbers and do not have any fractional or decimal part.
Floating-Point Constant: - The constants, which are used to representing very large or very small numeral values and
fractions is known as floating-point constants.
(iii) String constant: - A sequence of zero or more characters surrounded by double quotes is called string constant.
This can be also defined as an array of character constants.
(iv) Symbolic constant: - It is a constant that is represented by name (symbol) in the program. It make a program more
readable and protect it from side effects created by variable. In c++, there are two ways of creating symbolic constant:
const: - We can declare a C++ constant by writing const before the identifier’s data type. For example: - const int a =
10;
enum: - An enumerated data types provides a way for attaching names to numbers. In C++, enum automatically
enumerates a list of words by assigning them values 0, 1, 2 and so on. For example: height verylarge; Here verylarge is
of the type height.
Dynamic initialization of variables: - Dynamic initialization is mainly used in OOPL. In C we initialize a variable before using it.
But in C++, we can declare and initialize a variable simultaneously at the place where the variable is used for the first time. it
means, We initialize a variable at run time. Example: Float average = sum/t;
Reference Variables: - A reference variable provides an alternative name (alias) for previously defined variable. Syntax: data-type
& reference-name = variable-name Examples: - int amount = 100; int & total = amount; cout<< amount << total;
DATA TYPES
The kind of data that a variable may hold in a programming language is called the data type. There are two reasons for
distinguishing among data types. These are:
The compiler may use the proper internal representation for each type of the data.
The programmer designing the programs may use proper operators for each type of data.
The data types can be classified into the following three categories:
(a) User defined data type: - User defined data type enables a programmer to invent our data types and define what values it can
take on.
(b) Derived Data Type: - Derived data types are built from the basic integer and floating point data types. The array data type is
one example of derived data type.
(c) Built-in (Basic) Data Types: - The three built-in data types available in C++ are:
Integral Type – This can be further classified into:
int – int is the basic integer data type. It is treated as an integer in that it cannot hold fractional values.
char – This is a data type which can hold both the character data or the integer data. For example – char c;
Floating Type – This can be further classified into:
float – float integers are not adequate for representing very large values of numbers and fractions. For this we need
floating-point types of data representation.
double – the word double stands for double precision. It is capable of representing a real number ranging from 1.7x10-
308
to 1.7x10308 hich gives twice as much precision as represented by a float.
Void Type – The void data type has two important purposes.
A function does not return a value and the other is to declare a generic pointer. Example – void func (a,b)
This informs the compiler that any attempt to use the returned value from func() is a mistake and should be flagged as
an error. For example – func (x,y)
Array: - Array is the collection of same types of elements with unique name. array allocates contiguous space in memory
subscript or index of an array is started with 0 and up to size-1.
Array is a data structure (Static). Data structure enables us to store and manipulate organized collection of data.
If we have to handle more the one elements of same type for common purpose, then we prefer array rather creation of
individual variable to store and manipulate data.
For Example: - int x[3];
Array can be of: -
• Single Dimension
• Double Dimension
String: - String is the collection of characters thus we can say that it is example of character array.
Declaration of Single Dimension Array: -
NOTES BY –BALJEET SINGH SINWAR
28
OBJECT ORIENTED PROGRAMMING THROUGH C++
Syntax: Data type <Array Name> [Size]
Declaration of Double Dimension Array: -
Syntax: Data type <Array Name> [Row][Column]
OPERATORS
An operator operates on one or more variables and performs an action. It consists of words or symbols. Example: +, -, /,
*
The Operators can be classified into following categories:
(i) Arithmetic Operator (ii) Relational Operator (iii) Boolean Logical Operator (iv) Assignment Operator
(i) Arithmetic Operators: - An arithmetic operator is a symbol which performs operations such as addition, subtraction,
multiplication etc. on numbers n the form of data.
Operator Symbol Form Operation
Multiplication * x*y x multiplied by y
Division / x/y x divided by y
Modulus % x%y remainder of x /y
Addition + x+y x added by y
Subtraction - x-y x subtracted by y
Increment operator ++ a++ Firstly assign then increment a by 1
++a Firstly increment by 1 then assign
Decrement operator -- a-- Firstly assign then decrement a by 1
--a Firstly decrement by 1 then assign
(ii) Relational Operators: - Relational operators are used to compare the values of two variables.
Operator Symbol Form Operation
Equal to == x==y The result is 1 if value of x is equal to y
Greater than > x>y The result is 1 if value of x is greater than y
Greator than or equal to >= x>=y The result is 1 if value of x is greater than or equal to
y
Less than < x<y The result is 1 if value of x is less than y
Less than or equal to <= x<=y The result is 1 if value of x is less than or equal to y
Not equal to != x!=y The result is 1 if value of x is not equal to y
(iii) Boolean logical Operators: - These operators operate only one Boolean operand, i.e. those operands which have either
value 1 (true) or 0 (false).
THE ? OPERATOR - The conditional or ternary-if-else operator (?:) is used for assigning a value to a variable after
checking a condition. Syntax: var = operand1 ? operand2 : operand3;
This means: If operand is true Then var = operand2 Else var = operand3
Operator Symbol Operation
Logical AND & The result is 1 only if the values of Boolean operands on either side
of it are true.
Short-circuit AND && Same as logical AND except that f the left operand is false it will not
bother to evaluate the right-hand operand.
Logical OR | The result is 1 if any one of the value of Boolean operands is true.
Short-circuit OR || Same as logical OR except that if the left operand is true, it considers
the result to be true and does not evaluate the right-hand operand.
Logical XOR ^ Perform exclusive OR on two operands.
Logical NOT ! Inverts the operands.
Ternary if-then-else ?: It is a conditional operator where ? stands for if and : stands for else.
(iv) Assignment Operator: - There are two different categories of assignment operators. These are:
Simple Assignment Operator – The equal to sign (=) is the simple assignment operator. It is of the following form.
var = expression;
Compound Assignment Operator – this operator is a short cut method for assigning values to a variable, when one
of the operands is this variable itself.
Operator Example Evaluation Operator Example Evaluation
+= a+=b a=a+b ^ a^b a=a^b
-= a-=b a=a-b | a|b a=a|b
*= a*=b a=a*b >> a>>b a=a>>b
/= a/=b a=a/b >>> a>>>b a=a>>>b
%= a%=b a=a%b << a<<b a=a<<b
& a&b a=a&b
Operator Precedence: - Precedence determines which operation will be performed first in an expression that comprises multiple
operators.
Operator Evaluation Operator Evaluation Operator Evaluation
NOTES BY –BALJEET SINGH SINWAR
28
OBJECT ORIENTED PROGRAMMING THROUGH C++
() [] Highest < <= > >= &&
! ~ ++ -- == != ||
*/% & ?:
+- ^ =
<< >> >>> |
Manipulators: - It is data object that used with the insertion and extraction operators. Manipulators are the set of functions which
are used to manipulate the output formats. The most commonly used manipulators are endl and setw. Example:
cout<<”a=”<<a<<endl;
Type Conversion And Type Casting Operators
The process of converting one data type to another is known as casting. Casting is done by placing the desired type in parentheses
to the left of the value to be converted. For example the following statement casts an int value to a char and the resulting char
value is then stored in the character variable c as seen below.
int a = 10; char c = (char) a;
Type Cast Operator: - C++ also provides an explicit or distinct type conversion operation with the help of operator is called a cast
operator. Example: average = (double) total_marks/( double) num_student;
CONSOLE I/O
(i) Output stream – Cout (Carry Out) It is used for output operation i.e. printing on the screen.
Output operator - << To print constant string which is given by user or print the value kept in specified variable.
(ii) Input stream – Cin (Carry In) It is used for input operation i.e. put data in specified variable.
Input operator - >> To accept data from keyboard and put in to specified variable.
Header File – iostream.h
CONDITIONAL STATEMENTS
1. If - else - This control statement is used to check a condition and if the condition returns true then it executed the statements
within following braces. If the condition returns false then the statements within braces after else will be executed.
Syntax: (Simple if - else)
if (Boolean expression)
{ Statements if expression returns TRUE; }
else
{ Statements if expression returns FALSE; }
Syntax: (Nested if - else)
if (Boolean expression 1)
{ if(Boolean expression 2)
{ Statements if both the above expression returns TRUE; }
else
{ Statements if first expression returns TRUE and second returns FALSE; }
}
else
{ if(Boolean expression 3)
{ Statements if first expression returns FALSE and third returns TRUE; }
else
{ Statements if first and third expression both returns FALSE. }
}
Syntax: (if - else ladder)
if (Boolean expression 1)
{ Statements if expression 1 returns TRUE; }
else if (Boolean expression 2)
{ Statements if expression 1 returns FALSE but 2 returns TRUE; }
.
else
{ Statements if all the above expression returns FALSE. }
2. Switch - case - This control statement is used to select a specific set of instructions to execute among various set of
instructions as per input supplied to a single variable.
Syntax: switch (variable)
{ case constant1 : statement1; statement2; break;
case constant2 : statement3; statement4; break;
.
default : statements to execute if all the above conditions are false;
}
Note: Wrong switch-case expression
1. The case label must not be a floating point number. Case labels should always be integer constants or character
constants.
2. The case label must not be a string
NOTES BY –BALJEET SINGH SINWAR
28
OBJECT ORIENTED PROGRAMMING THROUGH C++
3. The case label cannot be another identifier but can be a constant identifier.
4. The case label cannot be an expression.
LOOP STATEMENT
The Loop constructs - The loop or iteration construct, directs a program to perform a set of operation again and again until a
specified condition is achieved. This condition causes the termination of the loop. Programming language C contains three
statements for looping:
1. The while loop - This loop construct is used to execute the certain set of instructions till the conditions with while command
returns true. As soon as the condition becomes false the loop terminated. It is possible that if the condition returns false first
time then the loop will terminated without running the enclosed statements even a single time. If someone does not make
provision for terminating the loop inside the body of loop then it converted into infinite loop.
Syntax: while (Boolean expression returns TRUE or FALSE)
{ Statements require repeating if the expressions TRUE; }
2. The do...while loop - This loop is used to execute the enclosed statements must for single time, and then check the condition
followed by while. If the while returns true then the loop executed again and again.
Syntax: do {
Statements require to run minimum once and then as per expression;
} while (Boolean expression);
3. The for loop - This loop construct is used to execute a set of statements for a given number of times. Thus, it is a shorthand
method for executing statements in a loop.
Syntax: (a) for(initial condition; test condition; incrementer or decrementer)
{ statement1; statement2; }
(b) for(initial1, initial2...;test1, test2....,incr./decr.1, incr./decr.2 ...)
{ }
(c) for(;;)
{ Body of infinite loop; }
4. The break Statement - If we need to come out of a running program immediately without letting it to perform any further
operation in a loop, then you can use break control statement.
5. The continue statement - This keyword is used to repeat a set of statements again even if the statements contains an error.
6. The goto statement - This unconditional branching statement is used to transfer the control in a program from one point to
another point. e.g. goto label;
.
label: statements...;
7. The exit () function - It is defined in the <stdio.h> header file and is used to terminate the program execution immediately. It
takes the form: exit(status);
Where 'status' is the termination value returned by the program and is an integer. Normal termination usually returns
0, while any other number can be used to indicate the error type.
CHAPTER – 3
FUNCTIONS
Function
Function enables us to break a complex task in to small-small module and each module can be individually called whenever
required. Due to such feature complexity of problem can be reduced.
Declaration of Function: - The declaration of functions consists of its return type, name and number of arguments. Function
declaration is also called unction prototype. It has three main components:
Function name – The function name is any legal identifier followed by the parentheses without any spaces in between.
Function type – The function ‘type’ is the type of the returned value. if the function does not return a value, the type is
defined as void.
Arguments – The arguments come inside the parentheses, preceded by their types and separated by commas.
Function can be of:
• Library Function (System Defined)
• User Defined Function: - to implement user defined function in a program, we must have to do the following:-
Declaration of function – prototype massaging to compile
Definition of function – statement of function for its purpose
Calling of function from required position where the function is required it invokes.
Function can be of:-
1. Function with no argument and no return value. 2. Function with argument and return value.
Example: - void abc(void); Example: - int abc(int,int);
3. Function with argument and no return value. 4. Function without argument but return value.
Example: - void abc(int); Example: - int abc(void);
A function can be called in two ways: -
(i) Call by value: - Program to Demonstrate Call by value:
CHAPTER – 11
EXCEPTION HANDLING
Exception handling provides a way of transferring control and information to an unspecified caller that has expressed willingness to handle
exceptions of a given type. Exception of arbitrary types can be ‘throw and catch ‘and set of exceptions a function may throw can be
specified.
Exception handling handles run time errors. Mainly generated the run time errors are as follows:-
• logical:- poor understanding of given problem and procedure of solution.
• Syntax :- poor understanding of programming language.
• Exception:- arises when program executed due to:-
Illegal arithmetic expression like digit divided by zero. Array overflow. Array index out of bound. Incompatible
assignment etc.
It mechanism transfers control and information from a point of exception in a program to an exception handler associated with the try-
block. An exception handler will invoked only by a thrown expression in the code executed by the handler’s try-block.
C++ provides following keywords to deal with exception. These are:-
• Try: - try is basically, a block where exception is generated.
• Throw: - when exception is generated, it must be ‘throw’ is used to throw the exception. ‘throw’ is used in ‘try’ block.
• Catch: - catch () is also a block, where exception handler statements are defined. It is basically a function & accepts
exception that is thrown by throw.
# program to demo. Exception handling
void main()
{ int b,c;
cout<<”enter value of b & c”;
cin>>b>>c;
try{
if(c==0)
throw c;
else
cout<<b/c;
}
catch(int k)
{ cout<<”exception caught”<<k; }
}
# program to demo. Exception handling with multiple catch
void test(int) if(k==3)
void main() { throw 9; }
{ int n; cout<<”enter the no.s[1,2 or 3]”; }
cin>>n; test(n); catch(char nm)
} { cout<<”exception caught”<<nm; }
void test(int k) catch(int m)
{ try { { cout<<”exception caught”<< m; }
if(k==1) catch(float n)
{ throw ‘x’;} { cout<<”exception caught”<<n; }
if(k==2) }
{ throw 12.3; }
CHAPTER – 12
CLASS LIBRARIES
Class Libraries: - C++ provides a library of data structures. Standard C++ includes its own built-in container class library.
String Class: - The string class stores the string as a character array and it includes a field that stores the size of the array. In order to use
this class we need to place the statement: #include<string>
Constructors
String() It creates an empty class. Syntax: string s1;
String s2(“kanak”) Initialize the string with a character array.
String s1(s2) Initialize a string (say s1) from another string (say s2) using the statement
String s1(6, ‘m’) Initialize a string as a repeated sequence of characters using the statement
Function