object oriented programming through c++

40
2 8 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++, NOTES BY –BALJEET SINGH SINWAR

Upload: tuniya4

Post on 16-Nov-2014

914 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++CHAPTER – 1

INTRODUCTION TO OBJECT ORIENTED PROGRAMMING (OOP)INTRODUCTIONWhat 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 OOPsObject 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. EncapsulationADVANTAGE 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 OBJECTClass: - 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 ENCAPSULATIONInheritance:-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 BINDINGIt 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

NOTES BY –BALJEET SINGH SINWAR

Page 2: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++#iinclude <iostream.h>void main(){

int x,y,z;cout<<” enter two integer no.”;cin>>x>>y;

z=x+y;cout<<” total is :”<< z<< endl;

}

NOTES BY –BALJEET SINGH SINWAR

Page 3: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++Program statements: - C++ has the following types of program statement:

(i) Declaration statement (ii) Assignment statement (iii) Function call statement (iv) Return statementComments – 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 – 2ELEMENTS OF C++ LANGUAGE

TOKENS & IDENTIFIERSTokens – 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 structbreak else long default goto catch switchcase enum register do if private typedefchar extern return asm new try unionconst float short operator this inline unsignedtemplate static signed throw delete volatile voidprotected 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 CONSTANTSVariable: - 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:Backslash Character Meaning Backslash Character Meaning\a Produces an audible alert signal. \r Prints a carriage return.\b Moves the curser back one

space.\t Prints a horizontal tab.

\f Moves the cursor to the next \v Prints a vertical tab.

NOTES BY –BALJEET SINGH SINWAR

Page 4: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++page.

\n Print a new line.

(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: -

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:

NOTES BY –BALJEET SINGH SINWAR

Page 5: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++(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 OperationMultiplication * x*y x multiplied by yDivision / x/y x divided by yModulus % x%y remainder of x /yAddition + x+y x added by ySubtraction - x-y x subtracted by yIncrement operator ++ a++ Firstly assign then increment a by 1

++a Firstly increment by 1 then assignDecrement 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 OperationEqual to == x==y The result is 1 if value of x is equal to yGreater than > x>y The result is 1 if value of x is greater than yGreator than or equal to >= x>=y The result is 1 if value of x is greater than or equal to

yLess than < x<y The result is 1 if value of x is less than yLess than or equal to <= x<=y The result is 1 if value of x is less than or equal to yNot 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 = operand3Operator Symbol OperationLogical 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() [] Highest < <= > >= &&! ~ ++ -- == != ||* / % & ?:+ - ^ =<< >> >>> |

NOTES BY –BALJEET SINGH SINWAR

Page 6: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++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 OperatorsThe 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 STATEMENTS1. 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 expression1. 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 string3. The case label cannot be another identifier but can be a constant identifier.4. The case label cannot be an expression.

LOOP STATEMENTThe 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:

NOTES BY –BALJEET SINGH SINWAR

Page 7: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++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 – 3FUNCTIONS

FunctionFunction 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.Example: - void abc(void);

2. Function with argument and return value.Example: - int abc(int,int);

3. Function with argument and no return value.Example: - void abc(int);

4. Function without argument but return value.Example: - int abc(void);

A function can be called in two ways: -(i) Call by value: - Program to Demonstrate Call by value:

NOTES BY –BALJEET SINGH SINWAR

Page 8: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++#include<iostrem.h>#include<conio.h>void exchange(int,int); /*Declaration of function*/void main( ){

int a,b;cout<<”Enter Two Integers”;cin>>a>>b;exchange(a,b);cout<<”a=”<<a<<endl;cout<<”b=”<<b;

getch( );}Void exchange(int k,int l){

int m;m=k;k=l;l=m;cout<<”a=”<<a<<endl;cout<<”b=”<<b;

}(ii) Call by reference: - In call by reference address of variable is passed as an argument i.e. why actual value can be used by the referenced module/function.

Major difference between call by value and call by reference function is, in call by value, formal copy specified argument is available to use, but in call by reference, actual value of specified argument is available to use./*Program to Demonstrate Call by reference*/

void exchange(int, int);void main(){

int a,b;cout<<”enter two integer value”;cin>>a>>b;exchange(&a,&b);cout<<”a=”<<a<<endl;cout<<”b=”<<b;

}

void exchange(int *p,int *q){

int t;t=*p;*p=*q;*q=t;cout<<”a=”<<*p<<endl;cout<<”b=”<<*q;

}

REFERENCE VARIABLES AND ARGUMENTSOverload Function: - Overloading refers to the use of the same thing for different purposes. C++ permits overloading of functions. In overloaded function, number of arguments and types of arguments are necessary consideration.

The function declaration, definition and calling of the functions are done with the same function name but with the different data arguments. The function overloading thus achieves a greater flexibility in a program.

Suppose, we have to add two integers as well as two floating point numbers and we have to make functions for that. We can create two functions with same name and number of argument and types of argument will be different.For example: -

Void sum(int, int);Void sum(float, float);

Program to demo the function overloading: -#include<iostream.h>#include<conio.h>Void sum(int, int);Void sum(float, float);Void main( ){ int x,y;

float k,l;cout<<”Enter two integers”;cin>>x>>y;cout<<”Enter two floating point number”;cin>>k>>l;sum(x,y);sum(k,l);

}Void sum(int, int){

int z;z=x+y;cout<<”Sum=”<<z;

}Void sum(float, float){

float m;m=k+l;cout<<”Sum=”<<m;

}Inline Function: - Inline function is almost similar to macros. Inline function declares and defines with ‘inline’ keyword.Inline means request to the compiler, compiler may accept or ignore the request. If the requested function satisfies the inline criteria i.e. function body should contain least statements. Inline function is not executed the like a member function means that no need to transfer control from calling point to definition and vice-versa. But it would be the job/responsibility of a compiler to available that the statement(s) at calling position.Inline Function Demonstration: -#include<iostream.h>#include<conio.h>Class xyz{

Private:Int x,y;

Public:

Xyz( ){

x=5;y=55;

}Inline int sum( ){

NOTES BY –BALJEET SINGH SINWAR

Page 9: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++return x + y;

}Void show( );

};Void xyz :: show( ){

Cout<<”x=”<<x<<endl;Cout<<”y=”<<y;

}Void main( ){

Xyz xx;xx.show( );cout<<”Sum=”<<xx.sum( );

}

CHAPTER – 4OBJECTS AND CLASSES

CLASS AND OBJECTSClass – Class is the way to define/declare the attribute (Data Member) and functionality of an object.Definition of Class – A class is a user defined data type which holds both the data and function. The internal data of a class is called member data and the functions are called member functions.Access Specifier: - Private – Data members and member functions are declared under private part cannot be accessed directly through its

object. Public – Data members and member functions are declared under public part can access be directly through its object. Protected – protected accessibility means that members within a call can be accessed by member functions declared by

that class and any classes “inherited” from that class.Class Declaration: - The class keyword defines a class where all data members are private by default, unless we specify change them using the public or protected keywords. For example:Class kanak /*class declaration*/{ int name; /*Private by default*/ }Class Function Definition: - Class functions declared within the lass operate on the data members of the class. We may define a member function within the class declaration or declare it inside the class and define it outside the class.(i) Member function definition inside the class declaration – A function declared as a member of a class is called a member function.

Such functions are normally declared as public in the class definition. The member functions operate upon three data types and accordingly are classified as: Manager Function – The manager functions are used to initialize and lean up the class objects. Constructors and deconstructors

are the two examples of member functions that carry out the manager functions. Accessor Functions – The accessor member functions are the constructor that returns information about an object’s current state. Implementor Functions – The implementor functions modify the data members and are also called asmutators.

(ii) Member Functions – We can declare a member function in two ways: It is defined on the member function within the class declaration. To define the function within a class, simply add the function

directly to the class. Example – Class point{ private:

int x; int y;public:

int position(){ return x; }

}

We declare a function inside the lass and define it outside the class. Example:Class point{ private:

int x; int y;int position()

}int point :: position() /*function position() belongs to class point*/

{ return x; }(iii) Scope Resolution Operator - C++ supports a mechanism to access a global variable from a function in which a local variable is defined

with the same name as a global variable. It is achieved using the scope resolution operator. Syntax for accessing a global variable using the scope resolution operator is shown in below :: global variable nameExample:-#include <iostream.h>int num=20;void main(){ int num=10;

cout<<”local=”<<num; // local variableCout<<”\nGlobal=”<<num; // global variableCout<<”\nGlobal+local=”<<:::num+num; //both local & global}

Object – Distinct real word entity.Class is declared/defined with ‘class’ keyword. A class can have data member(s) and member function(s).

Differences between Objects and Functions: - A function is usually written to perform only a single task suh as the calculation of a square root. A class offers a range of different services, each of which is activated by a different message. The function that an object carries out is thus determined by the message that is sent to it.Structure of c++ program: -

NOTES BY –BALJEET SINGH SINWAR

Page 10: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++1. Declaration or definition of class2. Definition of member function3. Definition of main function

Arrays of Objects: - An array is a user defined data type whose members are of the same data type and all the data members are of the same data type and all the data members are stored in adjacent memory locations.Case I => Single Object#include<iostrem.h>#include<conio.h>Class xyz{ private: int a,b;

Public:void getdata( );void putdata( );

};Void xyz :: getdata( ){ cout<<”Enter Two Integers”; cin>>a>>b;}Void xyz :: putdata( ){ cout<<”a=”<<a<<”b=”<<b; }Void main( ){ Xyz kk; kk.getdata( ); kk.putdata( ); getch( ); }Object instance: -

Space is separately allocated for data member with each instance of object. Space is allocated for member function only once and can be used by every object.

Case II => Multiple Object#include<iostrem.h>#include<conio.h>Class xyz{ private: int a,b;

Public:void getdata( );void putdata( );

};Void xyz :: getdata( )

{ cout<<”Enter Two Integers”; Cin>>a>>b;}Void xyz :: putdata( ){ cout<<”a=”<<a<<”b=”<<b; }Void main( ){ Xyz kk,zz,aa; kk.getdata( ); zz.getdata( );

aa.getdata( ); kk.putdata( ); zz.putdata( );aa.putdata( ); getch( );

}

Case III => Array Type object#include<iostrem.h>#include<conio.h>Class xyz{ private: int a,b;

Public:void getdata( );void putdata( );

};Void xyz :: getdata( ){ cout<<”Enter Two Integers”; cin>>a>>b;}

Void xyz :: putdata( ){ cout<<”a=”<<a<<”b=”<<b;}Void main( ){ xyz kk[3]; for(int i=0;i<3;i++)

{ Kk[i].getdata( ); }for(i=0;i<3;i++){ Kk[i].putdata( ); }getch( );

}

Case IV => Pointer type object#include<iostrem.h>#include<conio.h>Class xyz{ private: int a,b;

Public:void getdata( );void putdata( );

};Void xyz :: getdata( )

{ cout<<”Enter Two Integers”; cin>>a>>b;}Void xyz :: putdata( ){ cout<<”a=”<<a<<”b=”<<b;}Void main( ){ Xyz kk,*ptr; Ptr=&kk /*kk.getdata( ); => By name*/

ptr getdata( ); ptr putdata( ); getch( );}

Object as Function Arguments: - An object may be used as a function just like any other data type. This can be done in one of the following two ways:

(i) Pass-by-value - A copy of the entire object is passed to the function.(ii) Pass-by-reference – Only the address of the object is transferred to the function. When an address of the object is passed, the

called function works directly on the actual object used in the call.Returning Objects from Function: - Object an passed as a arguments to a function and function can also return the object./*Program to demo*/#include<iostream.h>class emp

NOTES BY –BALJEET SINGH SINWAR

Page 11: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++{ private:

int number; int age;public:

void getdata() void displaydate()};Void getdata(){ cout<< “number=”; Cin>>number;

Cout<< “age=”; Cin>>age;}Void displaydate(){ cout<< “\n number=”<<number<<endl;

cout<< “age=”<<age<<endl;}

Structure and Classes: - The difference between a structure and class lies in the validity of area of the members. In a class, by default, all members are private while in a structure they are public.Structure: - Collection of different data types of element is called structure.How to declare a structure?

Struct ss /*where ss is a tag name, a, b, k, ch are members of struct ss */{

Int a,b;Float k;Char ch;

}aa; /*aa is structure variable of type struct ss*//*’struct’ is the keyword to declare/define the structure*/

Structure variable can be of: -Single More than one (Multiple) Array type Pointer type

CHAPTER – 5CONSTRUCTORS AND DECONSTRUCTORS

CONSTRUCTORSBasic Constructors: - Constructor is a special member function, which name is similar to their class name. Constructor doesn’t return any value. Constructor can have argument. Constructor cannot be called as normal member function. Constructor is invoked through object instance. Constructor can be of: -

(i) Default Constructor – without argument (ii) Parameterized Constructor – with basic type argument(iii) Copy Constructor – with user defined type argument

Declaration and Definition: - Following are the main point than can be minded at the time of writing the constructors: The name of the constructor must be the same as that of its class name. It is declared with no return type (not even void). It is normally declared in the public access within the lass.Syntax:class user_defined_name{ private:

Data member;Public:

User_defined_name() //Constructor declaration{ ___________} other member functions;

}; //end of declaration(i) Default Constructors: - This constructor is a special member function with no arguments which initializes the data members i.e. the default constructor accepts no parameters. /*Program to demo Default constructor*/#include<iostream.h>#include<conio.h>class xyz{ private: int a,b;

public:xyz( ){ a=5; b=7;} Memory Allocationvoid show( );

};void xyz :: show( ){ cout<<”a=”<<a<<endl; cout<<”b=”<<b; }void main( ){ xyz xx;

xx.show( );}

(ii) Parameterized Constructor: - The constructors that can take arguments are called parameterized constructors. When a constructor is parameterized, we must provide appropriate arguments to the constructor.

When a constructor is parameterized, the object declaration with out parameter may not work. We must pass the initial values as arguments to the constructor. This can be done in two ways:

By implicit call – The implicit call is implemented as follows: student kanak (1200, 19); /*implicit call*/ This method is also called the shorthand method, and is used very often as it is shorter, looks better and easy to implement.

By Explicit Call – The following statement illustrates the explicit call for the parameterized constructor:Student mohan = student (1201, 20); /*explicit call*/

/*Program to demo Parameterized constructor*/#include<iostream.h>#include<conio.h>class xyz

{ private:int a,b;

public:

NOTES BY –BALJEET SINGH SINWAR

Separate space is allocated for each object with its data members.

Page 12: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++xyz( int x, int y){ a=x; b=y; }void show( );

};

void xyz :: show( ){ cout<<”a=”<<a<<endl; cout<<”b=”<<b; }void main( ){ xyz xx(5,7); xx.show( ); }

Overloaded Constructor Demonstration: -#include<iostream.h>#include<conio.h>class xyz{ private: int a,b;

public:Xyz( ){ a=x; b=y; }Xyz( int x, inty ){ a=x; b=y; }

Void show( );};Void xyz :: show( ){ Cout<<”a=”<<a<<endl; Cout<<”b=”<<b; }Void main( ){ Xyz bb; Xyz xx(5,7);

xx.show( ); bb.show( );}

Dynamic Initialization of Objects: - We can dynamically initialize objects. In the given program obj3 is dynamically initialized by using the value returned by the add() function called on object obj2. /*Program to demo*/#include<iostream.h>class c1{ public: int c;

c1 (int a){ c = a; }int add(){ return (c += 2); }

};

Void main(){ c1 obj1(1); //initializing object obj1 with c = 1

c2 obj2(2); //initializing object obje2 with c = 2cout<<obj1.c<< “\n”<<obj2.c;c1 obj3 (obj2.add()); //dynamic initialization of

object ibj3 with the value returned by add()cout<< “\n”<<obj1.c<< “\n”<<obj2.c<< “\n”<<obj3.c;

}Copy Constructor: - Copy constructors are used whenever an object of a class needs to be created temporarily. Copy constructors are used to initialize an object by another object of a similar class. Syntax: class_name :: class_name (class_name &ptr);/*Program to demo the copy constructor*/#include<iostream.h>#include<conio.h>class xyz{ private: int a,b;

Public:xyz( ){ a=1; b=2; }xyz(xyz.&p ){ a=p.a; b=p.b; }

Void show( );};Void xyz :: show( ){ Cout<<”a=”<<a<<endl; Cout<<”b=”<<b; }Void main( ){ Xyz xx; Xyz yy(xx);

xx.show( ); yy.show( );}

SHALLOW COPYING AND DEEP COPYINGThe default copy constructor simply copies each data member from the object passed as a parameter to the data member of the

new object. This approach of copying is known as Shallow Copying.Destructor is to clean the memory. If the ld object’s destructor cleans the integer in the free memory, the new object will continue

to point to this freed memory such a pointer is known as stray pointer, and the program will be error prone.To avoid creating such a stary pointer, one should create a customized copy constructor and allocate the memory as required.

After the memory is allocated, the old values can be copied into the new memory. This is known as Deep Copying.DYNAMIC CONSTRUCTORS

The constructors can also be used to allocate memory while creating object. This will enable the system to allocate the right amount of memory for each object when the objects are not of same size. This will result in saving of memory. Allocation of memory to objects at the time of their construction is known as Dynamic construction of objects. The memory is allocated with the help of the new operator. /*Program to demo dynamic constructor*/#include<iostream.h>class ABC{ int *roll,*age;

public:ABC(int k, int l){ roll= new int; age= new int;

*roll= k; *age= l;

}void display();

};void ABC::display(){ cout<<”roll=”<<*roll; cout<<”age=”<<*age; }void main(){ ABCxx(5,7); xx.display(); }

DESTRUCTORSIt is a special function, i.e. used to release the memory space, i.e. allocated by the object, when object is gone out of scope.Name of the Destructor is similar to the class, which it belongs. It does not have argument(s) and doesn’t return any value (no return type) Destructor is preceded by ~ (tiled) sign. Basically, Destructor is the feature, i.e. provided by c++.

Following points should be kept in mind while defining and writing the syntax for the destructor: A destructor function must be declared with the same name as that of the class to which it belongs. The first character of the destructor name must begin with a tilde (~). A destructor function is declared with no return types specified (not even void).

NOTES BY –BALJEET SINGH SINWAR

Page 13: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++ A destructor function must have public access in the class declaration.

Destructor Demonstration: -#include<iostream.h>#include<conio.h>class xyz{ private:

Int x,y;public:

xyz( ){ x=5; y=55; }~xyz( ){ cout<<”Object is destroyed”; }

Void show( );};Void xyz :: show( ){ cout<<”x=”<<x<<endl; cout<<”y=”<<y; }Void main( ){ xyz xx1, xx2, xx3; xx1.show( );

xx2.show( ); xx3.show( );}/*Order of releasing the space allocated by the object i.e. overlay xx2 xx3 xx1*/

CONSTRAINTS ON CONSTRUCTORS AND DESTRUCTORSConstructors have some special constraints or rules that must be followed while defining them. These are as follows:

Constructors should be declared in the public section. They do not have return types, not even void and therefore, they cannot return values. They are invoked automatically when the objects are created. They make implicit calls to the operators new and delete when memory allocation and cancellation, respectively, are required.

CHAPTER – 6OPERATOR 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){}

OVERLOADING UNARY OPERATORUnary operators are operators that act on only one operand, such as increment (++), decrement (--) and the unary minus operators.The following examples illustrate the overloading of Unary Operator:1. (-) operator overloading#include<iostream.h>#include<conio.h>class xyz{ private:

int x, y;public:

xyz()

{ X=5;Y=10; }Void show();Void operator –(){ X= -x; Y= -

y; }};

Void xyz :: show(){ cout<<”x=”<<x<<endl; cout<<”y=”<<y; }void main(){ xyz kk; kk.show();

-kk; kk.show(); getch();}

2. (++) operator overloading#include<iostream.h>#include<conio.h>class xyz{ private:

int x, y;Public:

xyz()

{ X=5;Y=10; }

Void show();Void operator ++(){ X= ++x; Y=

++y; }};

Void xyz :: show(){ cout<<”x=”<<x<<endl;

cout<<”y=”<<y; }Void main(){ xyz kk; kk.show();

++kk; kk.show(); getch();}

3. (--) operator overloading#include<iostream.h>#include<conio.h>class xyz{ private:

int x, y;Public:

xyz()

{ X=5; Y=10; }

Void show();Void operator --(){ X= --x; Y= --

y }};

Void xyz :: show(){ cout<<”x=”<<x<<endl; cout<<”y=”<<y; }Void main(){ xyz kk; kk.show();

--kk; kk.show(); getch();}

Operator Keyword: - We have used the operator keyword to overload the ++ operator. The return_type comes first, followed by operator keyword and the operator (++) and finally the argument list within parenthesis. This syntax tells the compiler to call this member function whenever the ++ operator is encountered, provided the operand is of type student.OVERLOADING BINARY OPERATORSThe following examples illustrate the overloading of Binary Operator:1. (+) operator#include<iostream.h> #include<conio.h>

NOTES BY –BALJEET SINGH SINWAR

Page 14: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++class xyz{ private:

int x, y;public:

void getdata();void putdata();xyz operator + (xyz kk){ xyz t; t.x = x + kk.x;

t.y = y + kk.y; return t;}

};

void xyz :: getdata(){ cout<<”Enter values for x and y”; cin>>x>>y; }void putdata(){ cout<<”x=”<<x<<endl; cout<<”y=”<<y; }void main(){ xyz aa, bb, cc; aa.getdata();

bb.getdata(); cc = aa + bb;aa.putdata(); bb.putdata();cc.putdata();

}

2. (-) operator#include<iostream.h>#include<conio.h>class xyz{ private:

int x, y;public:

void getdata(); void putdata();xyz operator - (xyz kk){ xyz t; t.x = x - kk.x;

t.y = y - kk.y; return t;}

};void xyz :: getdata(){ cout<<”Enter values for x and y”; cin>>x>>y; }void putdata(){ cout<<”x=”<<x<<endl; cout<<”y=”<<y; }void main(){ xyz aa, bb, cc; aa.getdata(); bb.getdata();

cc = aa - bb; aa.putdata(); bb.putdata();cc.putdata();

}

3. (*) operator#include<iostream.h>#include<conio.h>class xyz{ private:

int x, y;public:

void getdata(); void putdata();xyz operator * (xyz kk){ xyz t; t.x = x *kk.x;

t.y = y * kk.y; return t;}

};void xyz :: getdata(){ cout<<”Enter values for x and y”; cin>>x>>y; }void putdata(){ cout<<”x=”<<x<<endl; cout<<”y=”<<y; }void main(){ xyz aa, bb, cc; aa.getdata(); bb.getdata();

cc = aa * bb; aa.putdata(); bb.putdata();cc.putdata();

}

4. (/) operator#include<iostream.h>#include<conio.h>class xyz{ private:

int x, y;public:

void getdata(); void putdata();xyz operator / (xyz kk){ xyz t; t.x = x / kk.x;

t.y = y / kk.y; return t;}

};void xyz :: getdata(){ cout<<”Enter values for x and y”; cin>>x>>y; }void putdata(){ cout<<”x=”<<x<<endl; cout<<”y=”<<y; }void main(){ xyz aa, bb, cc; aa.getdata(); bb.getdata();

cc = aa / bb; aa.putdata(); bb.putdata();cc.putdata();

}

5. (%) operator#include<iostream.h>#include<conio.h>Class xyz{ private:

int x, y;public:

void getdata(); void putdata();xyz operator % (xyz kk){ xyz t; t.x = x % kk.x;

t.y = y % kk.y; return t;}

};void xyz :: getdata(){ cout<<”Enter values for x and y”; cin>>x>>y; }void putdata(){ cout<<”x=”<<x<<endl; cout<<”y=”<<y; }void main(){ xyz aa, bb, cc; aa.getdata(); bb.getdata();

cc = aa % bb; aa.putdata(); bb.putdata();cc.putdata();

}

The following examples illustrate the overloading of Relational Operator:1. (>) operator#include<iostream.h>class man

{ private:int age;

NOTES BY –BALJEET SINGH SINWAR

Page 15: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++public:

void getdata(); void operator > (man p) { if (age>p.age)

cout<<”Age of aa is greater than age of bb”;

elsecout<<”Age of bb is greater

than age of aa”;

}};void man :: getdata(){ cout<<”enter values for age”; cin>>age; }void main(){ Man aa, bb; aa.getdata();

bb.getdata(); aa>bb;}

2. (<) operator#include<iostream.h>class man{ private:

int age;public:

void getdata(); void operator < (man p) { if (age<p.age)

cout<<”Age of aa is less than age of bb”;

else

cout<<”Age of bb is less than age of aa”;

}};void man :: getdata(){ cout<<”enter values for age”; cin>>age; }void main(){ Man aa, bb; aa.getdata();

bb.getdata(); aa<bb;}

3. (==) operator#include<iostream.h>class man{ private:

int age;public:

void getdata(); void operator ==(man p) { if (age==p.age)

cout<<”Age of aa is equal to age of bb”;

else

cout<<”Age of bb is not equal to age of aa”;

}};void man :: getdata(){ cout<<”enter values for age”; cin>>age; }void main(){ man aa, bb; aa.getdata();

bb.getdata(); aa==bb;}

The following examples illustrate the overloading of Shift Operator:1. (<<) operator using friend function#include<iostream.h>class xyz{ private:

int a[3];public:

void getdata(); Friend ostream << (ostream, xyz);};void xyz :: getdata(){ for(int i=0;i<3;i++)

{ cout<<”Enter the element”; cin>>a[i]; }}ostream & operator (ostream kout, xyz p){ for(int i=0;i<3;i++)

{ kout<<p.a[i]; }return kout;

}void main(){ xyz xx; xx.getdata(); cout<<xx; }

2. (>>) operator using friend function#include<iostream.h>class xyz{ private:

int a[3];public:

void putdata(); Friend istream << (istream, xyz);};void xyz :: putdata(){ for(int i=0;i<3;i++)

{ cout<<a[i]; }

}istream & operator (istream kin, xyz p){ for(int i=0;i<3;i++)

{ kin<<p.a[i]; }return kin;

}void main(){ xyz xx; cin>>xx;

xx.putdata();}

Extra: (+) operator overloading using friend function#include<iostream.h>class xyz{ private:

int x, y;public:

void getdata(); void putdata();Friend xyz operator + (xyz, xyz);

};

void xyz :: getdata(){ cout<<”Enter the element”; cin>>x>>y; }void xyz :: putdata(){ cout<<”x=”<<x<<endl; cout<<”y=”<<y; }xyz operator + (xyz p, xyz q){ xyz t; t.x = p.x+q.x;

t.y = p.y+q.y; return t;}

NOTES BY –BALJEET SINGH SINWAR

Page 16: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++void main(){ xyz aa, bb, cc; aa.getdata(); bb.getdata();

cc = aa + bb; aa.putdata(); bb.putdata();

cc.putdata();}

Examples of Arithmetic overloadingAddition of Polar co-ordinates: - #include<iostream.h>class coordinate{ int x,y;

public:coordinate(int i, int j){ x=i; y=j;}coordinate operator +(coordinate obj){ coordinate temp(0, 0);

temp.x=x+obj.x;temp.y=y+obj.y; return temp;

}};void main(){ coordinate A(3,4), B(7,10);

coordinate C=A+B;}

Concatenation of String: -#include<iostream.h>#include<string.h>class String{ char *ptr; int len;

public:String(){ len=0; ptr=new char[++len]; }String (char *s){ len=strlen(s); ptr=new char[++len];

strcpy(ptr,s); }void display(); String operator +(String s);

};void String :: display(){ cout<<ptr; }String String :: operator +(String s){ String temp; strcpy(temp.ptr, ptr);

strcat(temp.ptr, s.ptr); return temp;}void main(){ String str1(“rat”); String str2 (“cat”);

String str3=str1 + str2; str3.display();}

Multiple Overloading: - We can put two classes together in the same program as well and C++ compiler would still know how to interrupt the + operator. it selects the correct function to call depending on the data type of the operands.DATA AND TYPE CONVERSIONConversion between Basic Types: - We need to forcibly convert one type into another. to do this, we have to use the cast operator. such a conversion is known as explicit conversion.

CHAPTER – 7DERIVED CLASS AND INHERITANCE

DERIVED CLASS AND BASE CLASSA base class is a class from which other classes are derived. And a derived class can inherit members from a base class.

DERIVED CLASS CONSTRUCTORSWhen a derived class object is created, we have to supply values that are required by the derived class as well as by the base class.

Inside a derived class constructor, the base constructor(s) is executed first before executing the statements in the body of the derived constructor. The general form a derived class constructor is the following:Derived_class_name (arg1, arg2, ….., argn);Base_class_name (arg1, arg2, …..);{ //body of the derived class }OVERRIDING THE MEMBER FUNCTIONS

When a derived class implements a function that has the same name as well as the same set of arguments as the function in the base class, it is called function overriding. /*Program to demo function overriding*/#include<iostream.h>class SuperA{ public:

void print(){ cout<< “I am a Base class’s function\n”; }

};class SubA : public SuperA{ public:

void print(){ cout<< “I am derived class’s function\n”;

SuperA :: print();}

};void main(){ SubA a; a.print(); }

INHERITANCEThis 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. There are following types of inheritance:(i) Single Inheritance (ii) Multiple Inheritance (iii) Multilevel Inheritance (iv) Hierarchical Inheritance (v) Hybrid

Inheritance(i) Single Inheritance : - A derived class has only one base class.

Syntax: class<derived class name>: <association with base class> <base class name>Case I – If the association between base and derived class is public:#include<iostrem.h>Class base

{ protected:int a, b, c;

NOTES BY –BALJEET SINGH SINWAR

Page 17: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++public:

void get1(); void put1();};class derived : public base{ int e, f;

public:void get2(); void put2();

};void base :: get1(){ cout<<”Enter the element”; cin>>a>>b>>c; }void base :: put1()

{ cout<<”a=”<<a<<endl; cout<<”b=”<<b<<endl;cout<<”c=”<<c;

}void derived :: get2(){ cout<<”Enter the element”; cin>>e>>f; }void derived :: put2(){ cout<<”e=”<<e<<endl; cout<<”f=”<<f; }void main(){ derived xx; xx.get1(); xx.get2();

xx.put1(); xx.put2();}

Case II – If the association between base and derived class is private:#include<iostrem.h>class base{ protected:

int a, b, c;public:

void get1(); void put1();};class derived : private base{ int e, f;

public:void get2(); void put2();

};

void base :: get1(){ cout<<”Enter the element”; cin>>a>>b>>c;}void base :: put1(){ cout<<”a=”<<a<<endl; cout<<”b=”<<b<<endl;

cout<<”c=”<<c;}void derived :: get2(){ cout<<”Enter the element”; cin>>e>>f; }void derived :: put2(){ cout<<”e=”<<e<<endl; cout<<”f=”<<f; }void main(){ derived xx; xx.get2(); xx.put2(); }

(ii) Multiple Inheritance: - A derived class more than one base classes.#include<iostream.h>

class xyz{ protected:

int x, y;public:

void getdata(); void putdata();};class abc{ protected:

int a, b;public:

void getdata1(); void putdata1();};class kbc: public xyz, public abc{ int k, b;

public:void getdata2(); void putdata2();

};void xyz :: getdata(){ cout<<”Enter the element”; cin>>x>>y; }void xyz :: putdata(){ cout<<”x=”<<x<<endl; cout<<”y=”<<y; }void abc :: getdata1(){ cout<<”Enter the element”; cin>>a>>b; }void abc :: putdata1(){ cout<<”a=”<<a<<endl; cout<<”b=”<<b; }void kbc :: getdata2(){ cout<<”Enter the element”; cin>>k>>b; }void kbc :: putdata2(){ cout<<”k=”<<k<<endl; cout<<”b=”<<b; }void main(){ kbc yy; yy.getdata(); yy.getdata1();

yy.getdata2(); yy.putdata(); yy.putdata1();yy.putdata2();

}(iii) Multilevel inheritance: - Derivation of a class from another derived class is called Multilevel Inheritance. In Multilevel Inheritance, at

least one class must have both characteristics i.e. base and derived.#include<iostream.h>class a{ protected:

int aa;public:

void get1(); void put1();};class b : public a{ protected:

int bb;public:

void get2(); void put2();};class c : public b{ int cc;

public:void get3(); void put3();

};void a :: get1(){ cout<<”Enter the element”; cin>>aa; }void a :: put1(){ cout<<”aa=”<<aa; }void b :: get2();{ cout<<”Enter the element”; cin>>bb; }void b :: put2(){ cout<<”bb=”<<bb; }void c:: get3(){ cout<<”Enter the element”; cin>>cc; }void c ::put3(){ cout<<”cc=”<<cc; }void main(){ c yy; yy.get1(); yy.get2(); yy.get3();

yy.put1(); yy.put2(); yy.put3();}

(iv) Hybrid Inheritance: - An inheritance has characteristics of more than one inheritance, called Hybrid inheritance.

NOTES BY –BALJEET SINGH SINWAR

Page 18: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++#include<iostream.h>class a{ protected:

int x, y;public:

void get1(); void put1();};class b: public a{ protected:

int a, b;public:

void get2(); void put2();};class d{ protected:

int p, q;public:

void get3(); void put3();};class c : public b, public d{ int k, b;

public:void get4(); void put4();

}void a :: get1(){ cout<<”Enter the element”; cin>>x>>y; }void a :: put1(){ cout<<”x=”<<x<<”y=”<<y; }void b :: get2(){ cout<<”Enter the element”; cin>>a>>b; }void b :: put2(){ cout<<”a=”<<a<<”b=”<<b; }void d :: get3(){ cout<<”Enter the element”; cin>>p>>q; }void d :: put3(){ cout<<”p=”<<p<<”q=”<<q; }void c :: get4(){ cout<<”Enter the element”; cin>>k>>b;}void c :: put4(){ cout<<”k=”<<k<<”b=”<<b;}void main(){ c yy; yy.get1(); yy.get2(); yy.get3(); yy.get4();

yy.put1(); yy.put2(); yy.put3(); yy.put4();}

(v) Hierarchical Inheritance: - An Hierarchical inheritance begins with root class and expends level to level.CHAPTER – 8

POINTERSADDRESSES AND POINTERS

A Pointer is a variable that holds the address of the location of another variable in the main memory of the computer. A pointer provides a way of accessing a variable without referring to the variable directly. Pointers are used when passing actual values is difficult or undesirable. Some reasons to use pointers are as follows: To return more than one value from a function. To pass arrays and string more conveniently from one function to another. To manipulate arrays more easily by moving pointers to them, instead of moving the arrays themselves. To create complex data structures, such as linked lists and binary trees where one data item must contain references to other data items. To communicate information about memory as in the function delete() which returns the location of free memory by using a pointer.Address of Operator (&) and Pointer Variables: - The operator ‘&’ is used to get the address f a variable. Program to demo the use of &.#include<iostream.h>main(){ int x; x=2;

cout<< “\naddress of memory location for x”<<x<< “is”<<&x<<endl;}Accessing the variable pointed to Pointer to void: - The operator (*) gives the value stored at a particular address. Hence this operator is also called “value of address” operator. The other names for this operator are “indirection operator” or “dereferencing operator”.//Program to demonstrating the use of value at address (*) operator#include<iostream.h>main(){ int x; x=2;

cout<< “\nvalue stored at address”<<&x<<”is”<<*(&x)<<endl;}POINTER AND ARRAYSCharacteristics of Array: - An array is a collection of similar elements. Before using array, its type and size must be declared. The first element in the array is numbered 0. The elements of the array are stored in contiguous memory locations. An array can be initialized at the same time when it is declared.Arrays of Pointers: - The arrays of int and float means that each element of the array contains elements of same data type, namely int type in the case of array of int. in the same way there can be an array f pointers. Since a pointer variable always contains an address, an array of pointers would also contain a collection of addresses. The addresses present in the array of pointers can be addresses of isolated variables or addresses of array elements or any other addresses.POINTERS AND STRING

The Pointer notation can be applied to strings also to the other arrays.Pointers to String Constant: - In the given program, a pointer being used to address a string constant.#include<iostream.h>void main()

{ char *str = “I am a string”;cout<<str; cout<<str[5];

NOTES BY –BALJEET SINGH SINWAR

Page 19: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++str++; cout<<str; }

Strings as Function Arguments: - The following program shows a string being used as a function argument.#include<iostream.h>void display(char *ptr){ cout<<ptr; cout<<ptr[5]; }

void main(){ char *str[6] = “I am a String”; display(str);}

Array of Pointers to String: - Like we have arrays of variables of type int, char, float etc., we can also get arrays of Pointers. The following program creates an array of pointers to strings.#include<iostream.h>void main(){ char *str[6] = {“kanak”, “vinay”, “uttam”, “ashish”, “vinod”, “arun”};

for(int i=0; I,6; i++){ cout<<str[i]<< “\n”; }

}

MEMORY MANAGEMENT USING NEW AND DELETE OPERATORnew: - new operator is used to create a heap memory space for an object of a class. The keyword new calls upon the function operator new() to obtain memory. Syntax: data_type *Pointer_name = new data_type

The new operator uses the type of figure out how many bytes are needed. The it finds the memory and returns the address.delete: - The delete operator is used to remve the variable space has been created by using the new operator dynamically. The keyword delete in fact calls upon the function operator delete() to release storage which was created using the new operator. Syntax: delete pointer;//Program to demonstrate the use of new and delete operators#include<iostream.h>void main(){ int *ptr_x = new int; int *ptr_y = new int;

int *ptr_mul = new int; int *ptr_div = new int;cout<< “\nType any two integers”<<endl;cin>>*ptr_x>>*ptr_y;*ptr_mul = (*ptr_x) * (*ptr_y);*ptr_div = *ptr_x/*ptr_y;cout<< “Product of (*ptr_x and *ptr_y) =”<<*ptr_mul<<endl;cout<< “Division of (*ptr_x by *ptr_y) =”<<*ptr_div<<endl;delete ptr_mul; delete ptr_div;

}POINTERS TO OBJECTS

A pointer can point to an object created by a class. The pointer to an object of class variable can be accessed in the following two ways: (*object_name).member_name = variable; Object_name member_name = variable;

In first case, we use the dot operator and the object. The parentheses are essential in this case because the member of class period (.) has a higher precedence over the indirection operator(*). In second case, we used the arrow operator () and the object pointer.Arrow Operator: - The pointer to the member of a class be expressed using in arrow operator. The arrow operator consists of a dash (-) and the greater than (>) sign. Syntax: object_name member_name = variable;This operator: - C++ uses a pointer called this to represent the object that invoked the member function. In other words we can say that this is a pointer that points to the object for which the member function was called.POINTERS TO POINTERS

A pointer to a pointer is a construct used frequently in more complex programs. To declare a pointer to a pointer, place the variable name after two successive asterisks (*). For instance int **z; declares z to be a pointer to an integer variable z.

CHAPTER – 9VIRTUAL FUNCTIONS

POLYMORPHISMIt includes the ability to use the same message to objects of different classes and make them behave differently.Thus we could define “+” for both the addition of numbers and the concatenation of characters, even through both these

operations are completely different, thus, polymorphism provides the ability to use the same word to invoke different methods/action according to similarity of meaning. It allows the programmer to define a base class that includes routines that perform standard operations on groups of related objects, without regard to the exact type of each object. There are two types:1. Compile time polymorphism : - The overloaded member functions are “selected for invoking” by matching the member of arguments and arguments-type. This information, viz. number of arguments types is known to the compiler at the compile time itself. Therefore, the selection of the appropriate function made the compile time only. This is known as early binding or static binding.2. Run time polymorphism : - In run time polymorphism, function is blind with their object at runtime not compile time. So that appropriate version of the function can be called run time polymorphism. It is also known as late binding.VIRTUAL FUNCTION

NOTES BY –BALJEET SINGH SINWAR

Page 20: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++C++ use to use same function in different levels of class hierarchy. But we have to make function virtual function is the

implementation of run time polymorphism. In run time polymorphism function is bin with their object at run time not compiling time.Program to achieve Run Time polymorphism/Late binding/Demo. Of virtual function#include<iostream.h>class xyz{ protected:

int x, y;public:

virtual void getdata(); virtual void putdata();};class abc : public xyz{ int a, b;

public:void getdata(); void putdata();

};void xyz :: getdata()

{ cout<<”Enter the value for x and y”; cin>>x>>y; }void xyz :: putdata(){ cout<<”x=”<<x<<endl; cout<<”y=”<<y; }void abc :: getdata(){ cout<<”Enter the value for a and b”; cin>>a>>b; }void abc :: putdata(){ cout<<”a=”<<a<<endl; cout<<”b=”<<b; }void main(){ xyz aa, *ptr; abc bb; ptr=&aa; ptrgetdata();

ptrputdata(); ptr=&bb; ptrgetdata(); ptrputdata();

}

Note: - abc bb; bb.getdata(); The statement overrides the getdata() member function of class xyz.Pure Virtual Function: - Pure virtual function o nothing in base class, where it is declared means that pure virtual function is declared in a base class without definition and contains Null. But it is necessary for their derived class to redefine it. A class contains pure virtual function, doesn’t need to instance its object, i.e. abstract class. Example:#include<iostream.h>class xyz{ Public:

Virtual void display() = 0;};class abc : public xyz{ private: int a, b;

Public:

abc(){ A=5; B=10; }void display();

};void abc :: display(){ cout<<”a=”<<a<<endl; cout<<”b=”<<b; }void main(){ abc xx; xx.display(); }

Static Member: - Initialized with zero at 1st instance of class. Normally with object instance separate space is allocated for their data members. But for static member space is allocated only once and shared by all objects.#include<iostream.h>class abc{ static int c; int m;

public:void getdata(int); void putdata();

};void abc :: getdata(){ M=x; C++; }

void abc :: putdata(){ cout<<”c=”<<c; }void main(){ abc xx, yy, zz; xx.putdata(); yy.putdata();

zz.putdata(); xx.getdata(17); yy.getdata(70);zz.getdata(101); xx.putdata(); yy.putdata();zz.putdata();

}Output: C=0 C=0 C=0 C=3 C=3 C=3Static Member Function: - Static Member function can access the static member. Static member function is invoked with class name as: Class name :: function name() We know that static member is declared under class but it is not the part of any object. That’s why it needs to declare outside the class also as: datatype class name :: static member#include<iostream.h>class abc{ int c;

static int k;public:

void getdata(); void putdata();static void cal();

};void abc :: getdata(){ C=++k; }

void abc :: putdata(){ Cout<<”c=”<<c; }void abc :: cal(){ Cout<<”k=”<<k; }int abc :: k;void main(){ abc xx, yy; xx.getdata(); yy.getdata();

xx.putdata(); yy.putdata(); abc :: cal();}

FRIEND FUNCTION (BRIDGE FUNCTION)Friend function is the friend function of a class, under which it declares. Friend function declares with ‘friend’ keyword.

Friend function is not a member function of friend class. Means that friend function is an independent function. Friend function can use the private as well as public part of the friend class. Object(s) of the friend class are passed as an argument through friend function. Friend function can be friend of one class and more than one class.Friend Function Demonstration: - Example (1): -#include<iostrem.h>#include<conio.h>class xyz{ private: int a,b;

public:

void getdata( ); void putdata( );friend void sum(abc);

};void xyz :: getdata( ){ cout<<”Enter Two Integers”; cin>>a>>b; }

NOTES BY –BALJEET SINGH SINWAR

Page 21: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++void xyz :: putdata( ){ cout<<”a=”<<a<<”b=”<<b; }void sum(abc xx){ int z; z=xx.a+xx.b;

cout<<”Sum=”<<z;}void main( ){ xyz kk; kk.getdata( );

kk.putdata( ); sum(kk); getch( );}Example(2) –#include<iostream.h>#include<conio.h>class abc;class xyz{ private: int x,y;

public:void getxyz( ); void putxyz( );friend void sum(xyz,abc);

};void xyz :: getxyz( ){ cout<<”Enter Two Integers”; cin>>x>>y; }void xyz :: putxyz( ){ cout<<”x=”<<x<<”y=”<<y; }void abc :: getabc( ){ cout<<”Enter Two Integers”; cin>>a>>b; }void abc :: putabc( ){ cout<<”a=”<<a<<”b=”<<b; }void sum(xyz xx, abc kk){ int m,n; m=xx.x+kk.a; n=xx.y+kk.b;

cout<<”m=”<<m<<”n=”<<n;}void main( ){ xyz cc; abc ll; cc.getxyz( );

cc.putxyz( ); ll.getabc( );ll.putabc( ); sum(cc,ll); getch( );

}

MACROS AND INLINE FUNCTIONMacros: - The preprocessor directive #define can be used to create macro functions. A macro function is a symbol created using #define and that takes an argument, much like a function does. The preprocessor will substitute the definition string for whatever argument it is given. For example: #define TWICE(x) ((x) * 2) and then in our ode we write TWICE(2).Comparison between Macros and Inline Function: -

Macros can be confusing if they get large, because all macros must be defined on one line. Macros are not type safe. Any argument can be used with a macro, while this is not possible with inline functions which does strong

typing.CHAPTER – 10

STREAMSSTREAM CLASSES

C++ uses the following classes to implement streams: ios class: - This is the base class to

the input and output stream classes. istream and ostream classes: - These

are derived class from the ios class and posses specialized input and output stream behaviour, respectively. The istream class contain such functions as get(), getline() and read() while the stream class ontain such functions as put() and write().

iostream class: - This is derived from both the istream and the ostream classes and provides input and output functions for reading from the keyboard and writing to the monitor.

fstream classes: - These classes provide input and output from files. The ifstream class is used for creating input file, ofstream class for output file and fstream for files that will be used for both input and output. These classes are derived from istream, ostrem, iostream and from fstreambase.

STREAM CLASS HIERARCHYHEADER FILES

A header file provides a centralized location for the declaration of all extern variables, function prototypes etc. program files that must use or define a variable or a function must include the corresponding header files. For example, for using I/O functions, we need to include iostream.h file at the beginning of a program.

The header file “fstream.h” provides support for simultaneous I/O operations. It contains the classes ifstream and ofstream that provide I/O operations.ios FLAGS

C++ provides several methods for formatting the output. These are the following:Functions and flag defined in the ios class. Manipulators. User-defined output functions.

The ios class defines formatting flags and error-status flags. Some of the following formatting flags are as follows:Skipws: - Skip whitespace on input. Left – left-adjusted output. Right – right-adjusted output. Dec – convert to decimal. Oct – convert to octal. Hex-convert to hexadecimal. Showos –display + before positive integers. Stdio – flush stdout, stderror after insertion. Scientific – print floating point number in scientific notation.

NOTES BY –BALJEET SINGH SINWAR

Page 22: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++Following are the error flags: goodbit – no errors. eofbit – reached end of file. failbit – operation failed. badbit – invalid operation. hardfail – unrecoverable error.STREAM MANIPULATORS

Stream Manipulators are the following-instructions which are inserted directly into a stream. These can be used to set the formatting and displaying characteristics and other attributes of the stream objects. Come important manipulators are as follows: ws – turn on whitespace. ends – insert null character to terminate an output string. flush – flush the output stream. dec – convert to decimal. oct – convert to octal. hex – convert to hexadecimal. setw (int field-width) – set field width for output. setfill(int fill-character) – set fill character for output. set precision(int precision) – set preision. setiosflags(long formatting-flags) – set the specified flags. resetiosflags(long formatting-flags) – reset the specified flags.STRING STREAMS

The program that read and write strings from/to disk files, is given below:#include<fstream.h>void main(){ ofstream file_out(“test.txt”); //create file for output

file_out<< “This string will go into the file test.txt”;char arr[80];file_out.close(); //close the fileifstream file_in(“test.txt”); //create file for inputfile_in.getline (arr, 80); //read a line of textcout<<arr; //display the read line

}FILE HANDLINGTo carry out – cout Stream operator

cinread and write operationfrom console to main memory ifstream ofstream classes fstreami) ifstream: - It is used to create input file stream object.ii) ofstream: - Output file stream object.iii) fstream: - It is used to create both (input and output) file stream objects.Input stream: - Establishes the link between disk file and program file and carry out read operation from disk file to program file.Output stream: - Establishes the link between program file and disk file and carry out write operation from program file to disk file.How to create output stream object as constructor?

(i) ofstream output (“ABC”)int a;cout<<”Enter the data”;cin>>a;output<<a;

(ii) ofstream output;Program to create a text file#include<iostream.h>#include<conio.h>#include<fstream.h>void main(){ ofstream kk (“xyz”); kk<<”Patna”;

kk<<”Ranchi”; kk<<”Kolkata”;kk<<”Delhi”; kk<<”Mumbai”;kk.close(); int n = 80;

char ch[n]; ifstream input (“xyz”);while (input){ input.getline (ch, n);

cout<<ch;}input.close();

}

Program to create more than one text file with single stream object#include<iostream.h>#include<conio.h>#include<ifstrem.h>void main(){ ofstream kk; kk.open (“City”);

kk<<”Patna”; kk<<”Ranchi”; kk<<”Kolkata”; kk<<”Delhi”; kk<<”Mumbai”; kk.close();kk.open (“Rajdhani”); kk<<”Bihar”; kk<<”Jharkhand”;kk<<”West Bengal”; kk<<”New Delhi”;

kk<<”Maharastra”;

kk.close(); ifstream ll; int n = 80; char ch; ll.open (“City”);

while(ll){ ll.getline (ch, n); cout<<ch;}ll.close(); ll.open(“Rajdhani”);while(ll){ ll.getline(ch, n); cout<<ch;}

File Method of writing and reading

NOTES BY –BALJEET SINGH SINWAR

Page 23: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++(i) Text file Line by line(ii) Sequential Char by char(iii) Object By blockBinary read/write operations with fileFunction for read/ write operation: -get()put()read()write() get() and put() are used to perform sequential (character by character) read and write operation. read() and write() are used to perform block (object) writing in file as well as read from file. To open file in binary mode: -

Syntax: stream object.open (“filename”, ios :: out);Here file is opened for both function.

Program to demonstration sequential read/write operations using get() and put() function: -#include<iostream.h>#include<conio.h>void main(){ char nm[15]; cout<<”Enter the string”;

cin>>nm; int length = strlen(nm);fstream ff; ff.open (“abc”, ios :: in|ios :: out);for(int i=0;i<length;i++)

{ ff.put(nm[i]); }ff.seekg(0); /*To reset the get pointer at beginning

of file*/char ch;{ ff.get(ch); cout<<ch; }getch();

}Read and write functions:Syntax of read(): - input stream object.read((char*) & object, size of (object))Syntax of write(): - output stream object.write ((char*) & object, size of (object))Example: - #include<iostream.h>#include<conio.h>class emp{ int empno, sal; char desig[15], name[20];

public:void getdata(); void putdata();

};void emp :: getdata(){ cout<<”Enter emp no”; cin>>empno;

cout<<”Enter salary”; cin>>sal;cout<<”Enter Designation”; cin>>design;cout<<”Enter employee name”; cin>>name;

}void emp :: putdata(){ cout<<”Employee Name”<<name<<endl;

cout<<”Employee No”<<empno<<endl;

cout<<”Designation”<<design<<endl;cout<<”Employee salary”<<sal;

}void main(){ emp ee[10]; fstream ff;

ff.open(“employee”, ios :: in|ios :: out);for(int i=0;i<10;i++){ ee[i].getdata();

ff.write((char*) & ee[i], size of (ee[i]));}for(i=0;i<10;i++){ ff.read((char*) & ee[i], size of (ee[i]));

ee[i].putdata();}ff.close(); getch();

}File Streams: -

creation & string of text file creation & string a file sequentially

Command line argumentC:\>KBC odd Even

Name of source file(c++ file name)void main(int argc, char *argv[]){

argv[0]=KBCargv[1]=oddargv[2]=Evenargc=3

}void main(int argc, char *argv[])

{ int a[6]={9,10,11,12,13,14};int i; ofstream ff, ff’;ff.open(“argv[1]”,ios::out);ff’.open(“argv[2]”,ios::out);if(argc!=3){ exit(0) }for(j=0;j<6;j++){ if(a[j]%2==0)

ff<<a[i];else

ff’<<a[j];}ffclose(); ff’close();

}

CHAPTER – 11EXCEPTION HANDLING

NOTES BY –BALJEET SINGH SINWAR

Page 24: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++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 handlingvoid 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 catchvoid test(int)void main(){ int n; cout<<”enter the no.s[1,2 or 3]”;

cin>>n; test(n);}void test(int k){ try {

if(k==1){ throw ‘x’;}if(k==2){ throw 12.3; }

if(k==3){ throw 9; }}catch(char nm){ cout<<”exception caught”<<nm; }catch(int m){ cout<<”exception caught”<< m; }catch(float n){ cout<<”exception caught”<<n; }

}

CHAPTER – 12CLASS 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>ConstructorsString() 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 statementString s1(6, ‘m’) Initialize a string as a repeated sequence of characters using the statementFunctionAssign() To reset a string’s values based on a substring of another string. Syntax: s1.assign(s2,1,2);Insert() To insert a string inside another. Syntax: s1.insert(2, “vinod”);Resize() To change the size of string. Syntax: s1.resize(20);Length() To determine the current length of string. Syntax: int len = s1.length();Find() To search a string for the position at which a substring starts.Stack Class: - The stack class operates much like the standard stacks. It is implemented as a template class, so we can make a stack a stack object of any data type. In order to use this class we need to place the statement: #include<stack>;

NOTES BY –BALJEET SINGH SINWAR

Page 25: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++Program to demo:#include<stack>#include <vector>int main(){

Stack<int, vector<int> s; //Make a stack using a vector container

//Push a couple of values on the stacks.push(1);s.push(2);

cout<<s.top()<<endl;//Now pop them offs.pop();cout<<s.top()<<endl;s.pop();return 0;

}Member FunctionBool empty() Returns true if the stack is empty, otherwise falseVoid pop() Removes the item at the top of the stackVoid push(const value_type& x) Pushes x onto the stackInt size() Return the number of elements in the stackStack_type top() Returns the item at the top of the stack.List Class: - This is also a templated data structure. In order to use this class we need to place # include<list>Member FunctionBool empty() Returns true if size is zeroList_type back() Returns a copy of the back elementList_type front() Returns a copy of the front elementVoid merge(anotherlist) Merges in the contents of another listVoid pop_front(element) Removes the front elementVoid push_front(element) Adds an element at the frontVoid push_rear(element) Adds an element at the backVoid remove(element) Removes ALL occurrences of the elementVoid reverse() Reverses the order of the listInt size() Gets the current number of lists elementVoid sort() Sorts the list elements (ascending order)Void swap(anotherlist) Swaps this list’s contents with the other listQueue Class: - This is also a template class. It includes the member functions discussed in the following sections. In order to use this class we need to place #include <queue>Member FunctionQueue_type back() Returns the item at the back of the queue.Bool empty() Returns true if the queue is empty, otherwise falseQueue_type front() Returns the item at the front of the queue.Void pop () Removes the item at the front of the queueVoid push (queue_type x)) Pushes x onto the back of the queue.Int size() Returns the number of elements on the queueMicrosoft Foundation Classes (MFC): - MFC is an extensive C++ class library designed for creating Windows GUI programs. The MFC simplifies writing these programs, and it provides many high-level features that can save our time for coding effort.

CHAPTER – 13ADVANCE CLASSES

TEMPLATESTemplate is an advance feature in C++ that allows a single function or class to handle more than one data types.

Generic Function: - There may be times when we duplicate a function just because we wanted it to support parameters of a different data type. For example, the following function compare(), compares two values of type int and returns the larger value:int compare (int a, int b){ if (a>b)

return a;

elsereturn b;

}If the two functions appear in the same program, we must search for a different name for each of the functions. Such

complications are reduced by usages of templates. Thus, using templates, we can create generic functions.A Generic function is a function that could be used to work on different argument type.

Generic Class: - Templates allow us to define generic classes. A generic class is a class that can be used with any data type. Parameterized templates give us the ability to create a general class, and pass data-type as parameter to that class, in order to build specific instances.Template Class: - Template is the latest features of c++. Template enables us to define generic function & generic class and provide facilities for generic programming.

In generic programming parameters are generic means that parameters can be used for any data types.Program to demo. class templatestemplate<class t> class xyz

NOTES BY –BALJEET SINGH SINWAR

Page 26: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++{ t a,b;

public:xyz(t x,t y){ a=x; b=y;}void display();

};void xyz::display()

{ cout<<”a=”<<a; cout<<”b=”<<b;}void main(){ xyz<int,int>aa(5,7);

xyz<float,float>bb(13.2,15.7);aa.display; bb.display;

}

Program to demo class templates with two parameterstemplates<class t1,class t2>class xyz{ t1=a; t2=b;

public:xyz(t1=x,t2=y){ a=x; b=y;}void display();

};

void xyz::display(){ cout<<”a=”<<a; cout<<”b=”<<b;}void main(){ xyz<int,float>aa(5,7.3);

xyz<int,char>bb(6,’v’);aa.display(); bb.display();

}

Program to demo. function templatetemplate<class t>void exchange(t x,t y){ t z; z=x; x=y; y=z;

cout<<”x=”<<x<<”y=”<<y;}void main();{ int a,b; float j,k; cout<<”Enter two integers”;

cin>>a>>b; exchange(a,b);cout<<”Enter two floats”;cin>>j>>k; exchange(j,k);

}

template<class t1, class t2>void sum(t1 x,t2 y){ t2 z; z=x+y;

cout<<”sum=”<<z;}void main(){ int a; float b; cout<<”Enter integer”;

cin>>a; cout<<”Enter float”;cin>>b; sum(a,b);

}

Member function templatetemplate<class t>class xyz{ t a,b;

public:void getdata(); void putdata();

};template<class t>void xyz<t>::getdata()

{ cout<<”Enter two numbers”;cin>>a>>b;

}template<classt’>void xyz<t>::putdata(){ cout<<”a=”<<a; cout<<”b=”<<b; }void main(){ xyz pp; pp.getdata(); pp.putdata(); }

Template Function: - A template function is declared as follows: template <class T> void function-name (T a);o The function is declared to be a Template Function by the declaration on the top line.o Template function can have any name, just as other functions can.o Template function can also take objects of instances of a template class as arguments.o Template function can be an array of anu data type.

Example – template <class T>T compare (T a, T b){ if (a>b)

return a;

elsereturn b;

}

Overriding of Generic Functions: - If we want that a particular template function should behave differently with a particular data type, say int. this is possible using function overriding.

For this, we simply define a normal C++ function that has the same name as the function template but uses specific fixed data types rather than template types. This function will override the function template i.e. if we pass parameters of the types specified in the normal function, the compiler will call this function rather than generating a function based on the template.Program to demo: - #include <iostream.h>Template<class T>void print (T a){ cout<<”all data types\n”; }void print(float a) //overriding template function{ cout<<”float data type\n”; }Void main()

{ int x = 10;Float y = 10.56;Print(x); //function called with int data typePrint (y); //function called with float data typePrint (“Hello”); //function called with string data type

}

Containers and Nested Class: - A container class is a class that operates on a collection of zero or more objects of a particular type.

NOTES BY –BALJEET SINGH SINWAR

Page 27: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++The use of template facility in defining container classes, will allow us to define a single class that can work for all data types. For

example, we can define an object of container class Vector<int>. then, this object will contain a vector of integer values.Program to demo Container class:#include <iostream.h>Template <class T>Class Vector{ T *v; //type T vector

int size;Public:Vector (int m) //create a vector of size m

{ size = m; v = new T[size];}Vector (T *a) //create a vector from an array{ for(int i=0; i<size; i++)

{ v[i] = a[i]; }}

};Nested Class – The chNode class (guest class) might be a pointer to a char, etc. While the chList class (host class) may be implemented as list, array, vector, set etc. Suppose we want to define the chList as alinked-list of chNodes. We could define the class chList to contain pointers to object of type chNode.

We can make ChList as supervisor of chNode, by inserting ChNode within ChList. This is called class nesting.Program to demo nested class: - #include<iostream.h>Class ChList{ Protected:

Class ChNode //Hidden, protected node class{ public:

Char data; ChNode *next; ChNode();

};ChNode *head;Public:ChList(); ~ChList(); int AddtoFront (char &c);int RmvHead (char &c); int IsEmpty(); int IsFull();

};Objective Question(1) A c++ operands must start with a lower character.(2) A return statement in a function transfer control from the function to the point of its invocation.(3) All pre-process directives must start with # sign.(4) Counting of elements in a c++ array starts from zero.(5) A character string must be terminated with a NULL character.(6) The non-member function accesses the data member of a class called friend function.(7) The #define directory is used to define symbolic constants.(8) A special function namely catch is used to catch the exception that is thrown by throw.(9) Constructor is used to initiate the object with instance.(10) A function namely destructor releases the memory i.e. occupied by an object, when gone out of scope.Access voiletionclass xyz{ int a,b;

protected:int x,y; public:int z; void get1(); void put1();

};class ABC:public xyz{ int J,K;

public:

void get2(); voidput2();};void main(){

ABC xx; -------(i) xx.a=15;-------(ii)xx.z=13;-------(iii) xx.put1();------(iv)xx.y=21;-------(v) xx.J=25;-------(vi)xx.put2();------(vii)

}

(v) y is a protected data member of base class xyz. so it cannot be access directly by the object of its derived class.(ii) It is a private data member of base class xyz and cannot be accessed even their own object.(vi) Same reason as describe in(ii).Class Libraries

c++ provides string class to implement all the features associated with string.#include<string>

Constructor :-->(ii) string s1;

we can declare string object/string(empty)using default constructor.(iii) Initialize the string with a character array.

string s2(“Polytechnic”);(iv) Initialize string with another string.

string s1(s2);(v) Initialize a string with repeated sequence of characters.

string s1(6,’A’);Overloaded operator :-->

(i) The Assignment operator(=)Lopies the string on the right side into the string on the left side of the operator =.Example--> string s1,s2;

s2=”ABC”s1=s2

(ii) Comparison operator(<,<=,>,>=)Example--> string s1,s2;

NOTES BY –BALJEET SINGH SINWAR

Page 28: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++s1=”ABC”;s2=”KBC”;if(s1<s2){

-------}else{

------}

(iii) Addition operator(+) for concatenationExample--> string s1,s2,s3;

s1=”XYZ”;s2=”PVT Ltd”;s3=s1+s2;

Member Function(i) Assign()- This member function is used to reset the string as:

string s1; string s2(“ABCDEF”); s1.assign(s2,1,2);(ii) Insert()- Insert member function is used to insert set of characters in the string.

string s1; s1.insert(2,”forest”);(iii) resize()- This member function is used to change the size of the string.

string s1; s1.resize(5);(iv) Length()- It is used to calculate current length of the string.

string s1(“KBC”); int l= s1.length();List class--> #include<list>member functions:-

(i) bool empty() :--> This member function returns true if the size of list is zero.(ii) void pop_front() :--> This member function is used to delete the front element.(iii) void push_front(element) :--> This member function is used to add the element in front.(iv) void push_rear(element) :--> This member function adds the element at rear.(v) void remove(element) :--> This member function removes all occurrences of elements.(vi) void reverse() :--> This member function reverse the list.(vii) void sort() :--> This member function arranges the elements in the ascending order.

Stack class --> #include<stack>member functions:-

(i) bool empty() :--> returns true if stack is empty.(ii) void pop() :--> removes the item from top of the stack.(iii) void push(element) :--> adds the item at the top of the stack.(iv) int size() :--> returns total number of element in a stack.

Pointer -->Pointer is a special variable that can hold the address of another variable of same type.Pointer is associated with address.Using pointer, several features of c and c++ become easy/efficient to handle.Pointer provides another ways to work with a variable or function.We have to handle a variable with pointer then we must have to assign its base address to pointer.Variable- Variable is the popular element of programming language which is used to stored related types of data.Declaration of pointer :-

Datatype *pointer variable;Example

int *ptr, a;a=15;ptr=&a;

cout<<*ptr;Array handling through pointer :-

int s[6] ={1,3,5,7,2,4};int*ptr,1; ptr=&s[0];i=0;while(i<6)

{cout<<*ptr;ptr++;i++;

}String--> best example of Array(character)

*If we have to work with string ,then we use character array to hold and manipulate the string.Example- char *string 1=”How many bytes are allocated for short int”;

cout<<string1;cout<<string1[0];

Memory management using new and delete operators New operator New operator is used to create exactly needed memory space at runtime for specified type. In c this operation is performed by a function namely malloc(). When our program is compiled it is broken into four parts. i.e. program code ,global data, stack and heap(free memory area).Example- int *p=new int;

*p=5;Delete operator It is mainly used to releases the memory area. i.e. allocated by new operator. It is just like free() function of c.Example- delete p;

Int *p= new int;*p=5;Delete p;

NOTES BY –BALJEET SINGH SINWAR

Page 29: Object Oriented Programming Through c++

28

OBJECT ORIENTED PROGRAMMING THROUGH C++

NOTES BY –BALJEET SINGH SINWAR