OBJECT ORIENTED PROGRAMMING THROUGH C

++
CHAPTER – 1 INTRODUCTION TO OBJECT ORIENTED PROGRAMMING (OOP)
INTRODUCTION What is “C++”? C++ is an object oriented programming language. In other words we can say that it is a Hybrid (All features of “C” can be directly implemented with “C++”) programming language or it is superset of “C”. What is the difference between “C” and “C++”? Point “C” Language “C++” Language Input/Output Through Library function Through stream (Object) BASIC CONCEPTS OF OOPs Object oriented programming language have developed in an evolutionary manner and have become very popular over past few year. C++ is one such language. It is necessary to understand some of the concept of used extensively in OOP. These include: 1. Object 2. Classes 3. Inheritance 4. Encapsulation ADVANTAGE of OOP OOP offers several benefits to the program designer and the user. • Through inheritance, we can eliminate redundant code and extend the use of existing classes. • The principle of data hiding helps the programmer to build secure programs that cannot be invaded by code in other parts of the program. • It is possible to have multiple instances of an object to co-exist without any interference. • It is easy to partition the work in a project based on objects. • It is possible to map objects in the problem domain to those in the program. • Software complexity can be easily managed. COMPARISION OF PROCEDURAL PROGRAMMING AND OOPs When we need to read data item in an object, we call a member functions in the object. The function will access data and return us the value. we cannot access data directly, because data is hidden and cannot be altered accidentally. Data and its functions are said to be encapsulated into a single entity. When we need to modify the data in an object, we need to know the functions that interact with it. Thus we use that function. This procedure simplifies in writing, debugging and maintaining a program. A C++ program thus consists of number of objects which communicate with each other by calling one another’s member functions. DEFINITION OF CLASS AND OBJECT Class: - The concept of class is best understood with an analogy. Class is the way to define/declare the attribute (Instance Variable) and functionality of an object. Object: - An object is the something that has a fixed shape or well defined boundary. In the ordinary sense, an Object is something which is capable of being seen. A object can be any one or all of the following: (a) A visible thing (b) Something that can be picked up by a person (c) Something towards which thought or action is directed CONCEPT OF INHERITANCE AND ENCAPSULATION Inheritance:-This feature of c++, supports re-usability means that existing class/old class can be extended by a new class. New class is called derived class and old class, on which a new class is created, is called base class. Encapsulation: - It is mechanism that associates the code and the data it manipulates into a single unit and keeps them safe from external interference and misuse. In c++, this is supported by a construct called class. An instance of class is known as an object, which represents a real word entity. OPERATOR OVERLOADING ‘C++’ provides feature to overload mostly arithmetic, relational and other operators. Overloaded means operator can be used in c++ program for addition work not existing task. For example existing function of – (minus) is to negate the digit. But we can use this operator to negate an object (i.e. the additional task of minus operator). Statements to perform additional task, are written under special function namely operator ( ), i.e. provided by c++. Syntax to use operator function: Return type operator <operator sign> (argument) { } DYNAMIC BINDING It means that the code links with program call is not known until the time of call at run time. Dynamic link libraries include predefined functions that are linked with application program when it is loaded dynamically, instead of when executable file is generated statically. It is also known as late binding. BASIC PROGRAM CONSTRUCTION #iinclude <iostream.h> int x,y,z; z=x+y; void main() cout<<” enter two integer no.”; cout<<” total is :”<< z<< endl; { cin>>x>>y; } Program statements: - C++ has the following types of program statement:

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
(i) Declaration statement (ii) Assignment statement (iii) Function call statement (iv) Return statement Comments – Comments can be included in a program in three different ways in C++ as given below: Type Usages /* */ All characters between /* and */ are ignored. // All characters after the // up to end of the line are ignored.

CHAPTER – 2 ELEMENTS OF C++ LANGUAGE
TOKENS & IDENTIFIERS Tokens – Token is the smallest element of a program that is meaningful to the compiler. When we submit a java program to the java compiler, the compiler goes through the text and extracts individual tokens. Tokens can be categorized into the following five types: (a) Identifier (b) Keywords (c) Constants (d) Strings (e) Operators (a) Identifiers: – Identifiers refer to the names of variables, functions, arrays etc. given by a programmer. These are also the names of language objects, which can take many values, one at time. A variable is a name that the program associates with a storage location in memory. The following are the rule to name a Identifier:It can consist of any sequence of letter, digits and underscore (_).The first character should be a letter or an underscore. No other special characters are allowed. Reserved words (Keyword) cannot be used as name of identifier. It is case sensitive language, so (b) Keywords – The words which are reserved to do specific tasks at time of designing a programming language is known as Keywords. Following are the keywords: auto double int continue for virtual struct break else long default goto catch switch case enum register do if private typedef char extern return asm new try union const float short operator this inline unsigned template static signed throw delete volatile void protected class sizeof friend public while Character set: - There are two character sets in c++ language. These are (a) Source characters: - Using source characters, the source text is created. Example - Alphabets A to Z and _(underscore), Decimals 0 to 9, Special characters + - * ~ # % etc. (b) Execution characters/escape sequences: - These are interpreted at time of execution. The value of execution characters are defined as per the implementation. C++ provides the mechanism to get such characters that are invisible or difficult through execution characters. Execution characters and escape sequences are used inter-changeably. Following are the execution characters: Execution Character Meaning Result at execution time \0 End of string Null \n End of a line Moves the active position to the initial position of the next line. \r Carriage return Moves the active position to the initial position of the next paragraph. \f Form feed Moves the active position to the initial position of the next logical page. \v Vertical tab Moves the active position to the next vertical tabulation position. \t Horizontal tab Moves the active position to the next horizontal tabulation position. \b Backspace Moves the active position to the previous position on the current line. \a Alert Produces an audible alert \\ backslash Presents with a backslash \. VARIABLES AND CONSTANTS Variable: - A variable is a name that our program associated with a storage location in memory. After declaring a variable within a program we can assign it a value. (b) Constants – Constants are refer to fixed values that do not change during the execution of a program. Constants are the following types: (i) Backslash character constant: - The backslash (\) alters the meaning of the character that follows it. Following are the backslash character string and their meanings:

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
Backslash Character \a \b \f \n Meaning Produces an audible alert signal. Moves the curser back one space. Moves the cursor to the next page. Print a new line. Backslash Character \r \t \v Meaning Prints a carriage return. Prints a horizontal tab. Prints a vertical tab.

(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.7x10308 to 1.7x10308 hich gives twice as much precision as represented by a float.  Void Type – The void data type has two important purposes. A function does not return a value and the other is to declare a generic pointer. Example – void func (a,b) This informs the compiler that any attempt to use the returned value from func() is a mistake and should be flagged as an error. For example – func (x,y) Array: - Array is the collection of same types of elements with unique name. array allocates contiguous space in memory subscript or index of an array is started with 0 and up to size-1. Array is a data structure (Static). Data structure enables us to store and manipulate organized collection of data. If we have to handle more the one elements of same type for common purpose, then we prefer array rather creation of individual variable to store and manipulate data. For Example: int x[3]; Array can be of: • Single Dimension • Double Dimension String: - String is the collection of characters thus we can say that it is example of character array. Declaration of Single Dimension Array: -

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
Syntax: Data type <Array Name> [Size] Declaration of Double Dimension Array: Syntax: Data type <Array Name> [Row][Column] OPERATORS An operator operates on one or more variables and performs an action. It consists of words or symbols. Example: +, -, /, * The Operators can be classified into following categories: (i) Arithmetic Operator (ii) Relational Operator (iii) Boolean Logical Operator (iv) Assignment Operator (i) Arithmetic Operators: - An arithmetic operator is a symbol which performs operations such as addition, subtraction, multiplication etc. on numbers n the form of data. Operator Symbol Form Operation Multiplication * x*y x multiplied by y Division / x/y x divided by y Modulus % x%y remainder of x /y Addition + x+y x added by y Subtraction x-y x subtracted by y Increment operator ++ a++ Firstly assign then increment a by 1 ++a Firstly increment by 1 then assign Decrement operator -a-Firstly assign then decrement a by 1 --a Firstly decrement by 1 then assign (ii) Relational Operators: - Relational operators are used to compare the values of two variables. Operator Symbol Form Operation Equal to == x==y The result is 1 if value of x is equal to y Greater than > x>y The result is 1 if value of x is greater than y Greator than or equal to >= x>=y The result is 1 if value of x is greater than or equal to y Less than < x<y The result is 1 if value of x is less than y Less than or equal to <= x<=y The result is 1 if value of x is less than or equal to y Not equal to != x!=y The result is 1 if value of x is not equal to y (iii) Boolean logical Operators: - These operators operate only one Boolean operand, i.e. those operands which have either value 1 (true) or 0 (false).  THE ? OPERATOR - The conditional or ternary-if-else operator (?:) is used for assigning a value to a variable after checking a condition. Syntax: var = operand1 ? operand2 : operand3; This means: If operand is true Then var = operand2 Else var = operand3 Operator Symbol Operation Logical AND & The result is 1 only if the values of Boolean operands on either side of it are true. Short-circuit AND && Same as logical AND except that f the left operand is false it will not bother to evaluate the right-hand operand. Logical OR | The result is 1 if any one of the value of Boolean operands is true. Short-circuit OR || Same as logical OR except that if the left operand is true, it considers the result to be true and does not evaluate the right-hand operand. Logical XOR ^ Perform exclusive OR on two operands. Logical NOT ! Inverts the operands. Ternary if-then-else ?: It is a conditional operator where ? stands for if and : stands for else. (iv) Assignment Operator: - There are two different categories of assignment operators. These are:  Simple Assignment Operator – The equal to sign (=) is the simple assignment operator. It is of the following form. var = expression;  Compound Assignment Operator – this operator is a short cut method for assigning values to a variable, when one of the operands is this variable itself. Operator Example Evaluation Operator Example Evaluation += a+=b a=a+b ^ a^b a=a^b -= a-=b a=a-b | a|b a=a|b *= a*=b a=a*b >> a>>b a=a>>b /= a/=b a=a/b >>> a>>>b a=a>>>b %= a%=b a=a%b << a<<b a=a<<b & a&b a=a&b Operator Precedence: - Precedence determines which operation will be performed first in an expression that comprises multiple operators. Operator Evaluation Operator Evaluation Operator Evaluation

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
() [] ! ~ ++ -*/% +<< >> >>> Highest < <= > >= == != & ^ | && || ?: =

Manipulators: - It is data object that used with the insertion and extraction operators. Manipulators are the set of functions which are used to manipulate the output formats. The most commonly used manipulators are endl and setw. Example: cout<<”a=”<<a<<endl; Type Conversion And Type Casting Operators The process of converting one data type to another is known as casting. Casting is done by placing the desired type in parentheses to the left of the value to be converted. For example the following statement casts an int value to a char and the resulting char value is then stored in the character variable c as seen below. int a = 10; char c = (char) a; Type Cast Operator: - C++ also provides an explicit or distinct type conversion operation with the help of operator is called a cast operator. Example: average = (double) total_marks/( double) num_student; CONSOLE I/O (i) Output stream – Cout (Carry Out) It is used for output operation i.e. printing on the screen. Output operator - << To print constant string which is given by user or print the value kept in specified variable. (ii) Input stream – Cin (Carry In) It is used for input operation i.e. put data in specified variable. Input operator - >> To accept data from keyboard and put in to specified variable. Header File – iostream.h CONDITIONAL STATEMENTS 1. If - else - This control statement is used to check a condition and if the condition returns true then it executed the statements within following braces. If the condition returns false then the statements within braces after else will be executed. Syntax: (Simple if - else) if (Boolean expression) { Statements if expression returns TRUE; } else { Statements if expression returns FALSE; } Syntax: (Nested if - else) if (Boolean expression 1) { if(Boolean expression 2) { Statements if both the above expression returns TRUE; } else { Statements if first expression returns TRUE and second returns FALSE; } } else { if(Boolean expression 3) { Statements if first expression returns FALSE and third returns TRUE; } else { Statements if first and third expression both returns FALSE. } } Syntax: (if - else ladder) if (Boolean expression 1) { Statements if expression 1 returns TRUE; } else if (Boolean expression 2) { Statements if expression 1 returns FALSE but 2 returns TRUE; } . else { Statements if all the above expression returns FALSE. } 2. Switch - case - This control statement is used to select a specific set of instructions to execute among various set of instructions as per input supplied to a single variable. Syntax: switch (variable) { case constant1 : statement1; statement2; break; case constant2 : statement3; statement4; break; . default : statements to execute if all the above conditions are false; } Note: Wrong switch-case expression 1. The case label must not be a floating point number. Case labels should always be integer constants or character constants. 2. The case label must not be a string

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
3. The case label cannot be another identifier but can be a constant identifier. 4. The case label cannot be an expression. LOOP STATEMENT The Loop constructs - The loop or iteration construct, directs a program to perform a set of operation again and again until a specified condition is achieved. This condition causes the termination of the loop. Programming language C contains three statements for looping: 1. The while loop - This loop construct is used to execute the certain set of instructions till the conditions with while command returns true. As soon as the condition becomes false the loop terminated. It is possible that if the condition returns false first time then the loop will terminated without running the enclosed statements even a single time. If someone does not make provision for terminating the loop inside the body of loop then it converted into infinite loop. Syntax: while (Boolean expression returns TRUE or FALSE) { Statements require repeating if the expressions TRUE; } 2. The do...while loop - This loop is used to execute the enclosed statements must for single time, and then check the condition followed by while. If the while returns true then the loop executed again and again. Syntax: do { Statements require to run minimum once and then as per expression; } while (Boolean expression); 3. The for loop - This loop construct is used to execute a set of statements for a given number of times. Thus, it is a shorthand method for executing statements in a loop. Syntax: (a) for(initial condition; test condition; incrementer or decrementer) { statement1; statement2; } (b) for(initial1, initial2...;test1, test2....,incr./decr.1, incr./decr.2 ...) { } (c) for(;;) { Body of infinite loop; } 4. The break Statement - If we need to come out of a running program immediately without letting it to perform any further operation in a loop, then you can use break control statement. 5. The continue statement - This keyword is used to repeat a set of statements again even if the statements contains an error. 6. The goto statement - This unconditional branching statement is used to transfer the control in a program from one point to another point. e.g. goto label; . label: statements...; 7. The exit () function - It is defined in the <stdio.h> header file and is used to terminate the program execution immediately. It takes the form: exit(status); Where 'status' is the termination value returned by the program and is an integer. Normal termination usually returns 0, while any other number can be used to indicate the error type.

CHAPTER – 3 FUNCTIONS
Function Function enables us to break a complex task in to small-small module and each module can be individually called whenever required. Due to such feature complexity of problem can be reduced. Declaration of Function: - The declaration of functions consists of its return type, name and number of arguments. Function declaration is also called unction prototype. It has three main components:  Function name – The function name is any legal identifier followed by the parentheses without any spaces in between.  Function type – The function ‘type’ is the type of the returned value. if the function does not return a value, the type is defined as void.  Arguments – The arguments come inside the parentheses, preceded by their types and separated by commas. Function can be of: • Library Function (System Defined) • User Defined Function: - to implement user defined function in a program, we must have to do the following: Declaration of function – prototype massaging to compile  Definition of function – statement of function for its purpose  Calling of function from required position where the function is required it invokes. Function can be of:1. Function with no argument and no return value. 2. Function with argument and return value. Example: void abc(void); Example: int abc(int,int); 3. Function with argument and no return value. 4. Function without argument but return value. Example: void abc(int); Example: int abc(void); A function can be called in two ways: (i) Call by value: - Program to Demonstrate Call by value:

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
#include<iostrem.h> getch( ); #include<conio.h> } void exchange(int,int); /*Declaration of function*/ Void exchange(int k,int l) void main( ) { { int m; int a,b; m=k; cout<<”Enter Two Integers”; k=l; cin>>a>>b; l=m; exchange(a,b); cout<<”a=”<<a<<endl; cout<<”a=”<<a<<endl; cout<<”b=”<<b; 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 exchange(int *p,int *q) void main() { { int t; int a,b; t=*p; cout<<”enter two integer value”; *p=*q; cin>>a>>b; *q=t; exchange(&a,&b); cout<<”a=”<<*p<<endl; cout<<”a=”<<a<<endl; cout<<”b=”<<*q; cout<<”b=”<<b; } } REFERENCE VARIABLES AND ARGUMENTS Overload 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(int, int); { Void sum(float, float); int z; Void main( ) z=x+y; { int x,y; cout<<”Sum=”<<z; float k,l; } cout<<”Enter two integers”; Void sum(float, float) cin>>x>>y; { cout<<”Enter two floating point number”; float m; cin>>k>>l; m=k+l; sum(x,y); cout<<”Sum=”<<m; sum(k,l); } 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> Xyz( ) #include<conio.h> { Class xyz x=5; { y=55; Private: } Int x,y; Inline int sum( ) Public: {

NOTES BY –BALJEET SINGH SINWAR

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 – 4 OBJECTS AND CLASSES
CLASS AND OBJECTS Class – 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 int position() { private: { return x; } int x; int y; } public:  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 name Example:#include <iostream.h> cout<<”local=”<<num; // local variable int num=20; Cout<<”\nGlobal=”<<num; // global variable void main() Cout<<”\nGlobal+local=”<<:::num+num; //both local & global { int num=10; } 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

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
1. Declaration or definition of class 2. Definition of member function 3. 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> { cout<<”Enter Two Integers”; Cin>>a>>b;} #include<conio.h> Void xyz :: putdata( ) Class xyz { cout<<”a=”<<a<<”b=”<<b; } { private: int a,b; Void main( ) Public: { Xyz kk,zz,aa; kk.getdata( ); zz.getdata( ); void getdata( ); aa.getdata( ); kk.putdata( ); zz.putdata( ); void putdata( ); aa.putdata( ); getch( ); }; } Void xyz :: getdata( ) Case III => Array Type object #include<iostrem.h> Void xyz :: putdata( ) #include<conio.h> { cout<<”a=”<<a<<”b=”<<b;} Class xyz Void main( ) { private: int a,b; { xyz kk[3]; for(int i=0;i<3;i++) Public: { Kk[i].getdata( ); } void getdata( ); for(i=0;i<3;i++) void putdata( ); { Kk[i].putdata( ); } }; getch( ); Void xyz :: getdata( ) } { cout<<”Enter Two Integers”; cin>>a>>b;} Case IV => Pointer type object #include<iostrem.h> { cout<<”Enter Two Integers”; cin>>a>>b;} #include<conio.h> Void xyz :: putdata( ) Class xyz { cout<<”a=”<<a<<”b=”<<b;} { private: int a,b; Void main( ) Public: { Xyz kk,*ptr; Ptr=&kk /*kk.getdata( ); => void getdata( ); By name*/ void putdata( ); ptr getdata( ); ptr putdata( ); getch( ); }; } Void xyz :: getdata( ) 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

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
{ private: int number; public: int age; Cout<< “age=”; Cin>>age; } Void displaydate() { cout<< “\n number=”<<number<<endl; cout<< “age=”<<age<<endl; }

void getdata() void displaydate() }; Void getdata() { cout<< “number=”; Cin>>number; 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 – 5 CONSTRUCTORS AND DECONSTRUCTORS
CONSTRUCTORS Basic 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> void xyz :: show( ) class xyz { cout<<”a=”<<a<<endl; cout<<”b=”<<b; } { private: int a,b; void main( ) Separate space is allocated public: { xyz xx; for each object with its xyz( ) xx.show( ); data members. { a=5; b=7;} Memory Allocation } void 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> { private: #include<conio.h> int a,b; class xyz public:

NOTES BY –BALJEET SINGH SINWAR

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> Void show( ); #include<conio.h> }; class xyz Void xyz :: show( ) { private: int a,b; { Cout<<”a=”<<a<<endl; Cout<<”b=”<<b; } public: Void main( ) Xyz( ) { Xyz bb; Xyz xx(5,7); { a=x; b=y; } xx.show( ); bb.show( ); Xyz( int x, inty ) } { a=x; b=y; } 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> Void main() class c1 { c1 obj1(1); //initializing object obj1 with c = 1 { public: int c; c2 obj2(2); //initializing object obje2 with c = 2 c1 (int a) cout<<obj1.c<< “\n”<<obj2.c; { c = a; } c1 obj3 (obj2.add()); //dynamic initialization of int add() object ibj3 with the value returned by add() { return (c += 2); } 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> Void show( ); #include<conio.h> }; class xyz Void xyz :: show( ) { private: int a,b; { Cout<<”a=”<<a<<endl; Cout<<”b=”<<b; } Public: Void main( ) xyz( ) { Xyz xx; Xyz yy(xx); { a=1; b=2; } xx.show( ); yy.show( ); xyz(xyz.&p ) } { a=p.a; b=p.b; } SHALLOW COPYING AND DEEP COPYING The 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 void display(); { int *roll,*age; }; public: void ABC::display() ABC(int k, int l) { cout<<”roll=”<<*roll; cout<<”age=”<<*age; } { roll= new int; age= new int; void main() *roll= k; *age= l; { ABCxx(5,7); xx.display(); } DESTRUCTORS It 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 (~).

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
• A destructor function is declared with no return types specified (not even void). • A destructor function must have public access in the class declaration. Destructor Demonstration: #include<iostream.h> Void show( ); #include<conio.h> }; class xyz Void xyz :: show( ) { private: { cout<<”x=”<<x<<endl; cout<<”y=”<<y; } Int x,y; Void main( ) public: { xyz xx1, xx2, xx3; xx1.show( ); xyz( ) xx2.show( ); xx3.show( ); { x=5; y=55; } }/*Order of releasing the space allocated by the object i.e. ~xyz( ) overlay xx2 xx3 xx1*/ { cout<<”Object is destroyed”; } CONSTRAINTS ON CONSTRUCTORS AND DESTRUCTORS Constructors 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 – 6 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) { } OVERLOADING UNARY OPERATOR Unary 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> { X=5; Void xyz :: show() #include<conio.h> Y=10; } { cout<<”x=”<<x<<endl; class xyz Void show(); cout<<”y=”<<y; } { private: Void operator –() void main() int x, y; { X= -x; Y= { xyz kk; kk.show(); public: -y; } -kk; kk.show(); getch(); xyz() }; } 2. (++) operator overloading #include<iostream.h> { X=5; Void xyz :: show() #include<conio.h> Y=10; } { cout<<”x=”<<x<<endl; class xyz Void show(); cout<<”y=”<<y; } { private: Void operator ++() Void main() int x, y; { X= ++x; Y= { xyz kk; kk.show(); Public: ++y; } ++kk; kk.show(); getch(); xyz() }; } 3. (--) operator overloading #include<iostream.h> { X=5; Void xyz :: show() #include<conio.h> Y=10; } { cout<<”x=”<<x<<endl; class xyz Void show(); cout<<”y=”<<y; } { private: Void operator --() Void main() int x, y; { X= --x; Y= { xyz kk; kk.show(); Public: --y } --kk; kk.show(); getch(); xyz() }; } 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 OPERATORS The following examples illustrate the overloading of Binary Operator: 1. (+) operator

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
#include<iostream.h> }; #include<conio.h> void xyz :: getdata() class xyz { cout<<”Enter values for x and y”; cin>>x>>y; } { private: void putdata() int x, y; { cout<<”x=”<<x<<endl; cout<<”y=”<<y; } public: void main() void getdata(); { xyz aa, bb, cc; aa.getdata(); void putdata(); bb.getdata(); cc = aa + bb; xyz operator + (xyz kk) aa.putdata(); bb.putdata(); { xyz t; t.x = x + kk.x; cc.putdata(); t.y = y + kk.y; return t; } } 2. (-) operator #include<iostream.h> }; #include<conio.h> void xyz :: getdata() class xyz { cout<<”Enter values for x and y”; cin>>x>>y; } { private: void putdata() int x, y; { cout<<”x=”<<x<<endl; cout<<”y=”<<y; } public: void main() void getdata(); void putdata(); { xyz aa, bb, cc; aa.getdata(); bb.getdata(); xyz operator - (xyz kk) cc = aa - bb; aa.putdata(); bb.putdata(); { xyz t; t.x = x - kk.x; cc.putdata(); t.y = y - kk.y; return t; } } 3. (*) operator #include<iostream.h> }; #include<conio.h> void xyz :: getdata() class xyz { cout<<”Enter values for x and y”; cin>>x>>y; } { private: void putdata() int x, y; { cout<<”x=”<<x<<endl; cout<<”y=”<<y; } public: void main() void getdata(); void putdata(); { xyz aa, bb, cc; aa.getdata(); bb.getdata(); xyz operator * (xyz kk) cc = aa * bb; aa.putdata(); bb.putdata(); { xyz t; t.x = x *kk.x; cc.putdata(); t.y = y * kk.y; return t; } } 4. (/) operator #include<iostream.h> }; #include<conio.h> void xyz :: getdata() class xyz { cout<<”Enter values for x and y”; cin>>x>>y; } { private: void putdata() int x, y; { cout<<”x=”<<x<<endl; cout<<”y=”<<y; } public: void main() void getdata(); void putdata(); { xyz aa, bb, cc; aa.getdata(); bb.getdata(); xyz operator / (xyz kk) cc = aa / bb; aa.putdata(); bb.putdata(); { xyz t; t.x = x / kk.x; cc.putdata(); t.y = y / kk.y; return t; } } 5. (%) operator #include<iostream.h> }; #include<conio.h> void xyz :: getdata() Class xyz { cout<<”Enter values for x and y”; cin>>x>>y; } { private: void putdata() int x, y; { cout<<”x=”<<x<<endl; cout<<”y=”<<y; } public: void main() void getdata(); void putdata(); { xyz aa, bb, cc; aa.getdata(); bb.getdata(); xyz operator % (xyz kk) cc = aa % bb; aa.putdata(); bb.putdata(); { xyz t; t.x = x % kk.x; cc.putdata(); t.y = y % kk.y; return t; } } The following examples illustrate the overloading of Relational Operator: 1. (>) operator #include<iostream.h> class man

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
{ private: int age; public: void getdata(); void operator > (man p) { if (age>p.age) cout<<”Age of aa is greater than age of bb”; else cout<<”Age of bb is greater than age of aa”; 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 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 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++) 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]; } Extra: (+) operator overloading using friend function #include<iostream.h> class xyz { private: int x, y; public: void getdata(); void putdata(); } }; void man :: getdata() { cout<<”enter values for age”; cin>>age; } void main() { Man aa, bb; aa.getdata(); bb.getdata(); aa>bb; }

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; } 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; }

{ 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; } } 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(); } 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; }

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
xyz operator + (xyz p, xyz q) { xyz aa, bb, cc; aa.getdata(); bb.getdata(); { xyz t; t.x = p.x+q.x; cc = aa + bb; aa.putdata(); bb.putdata(); t.y = p.y+q.y; return t; cc.putdata(); } } void main() Examples of Arithmetic overloading Addition of Polar co-ordinates: #include<iostream.h> temp.x=x+obj.x; class coordinate temp.y=y+obj.y; return temp; { int x,y; } public: }; coordinate(int i, int j) void main() { x=i; y=j; } { coordinate A(3,4), B(7,10); coordinate operator +(coordinate obj) coordinate C=A+B; { coordinate temp(0, 0); } Concatenation of String: #include<iostream.h> }; #include<string.h> void String :: display() class String { cout<<ptr; } { char *ptr; int len; String String :: operator +(String s) public: { String temp; strcpy(temp.ptr, ptr); String() strcat(temp.ptr, s.ptr); return temp; { len=0; ptr=new char[++len]; } } String (char *s) void main() { len=strlen(s); ptr=new char[++len]; { String str1(“rat”); String str2 (“cat”); strcpy(ptr,s); } String str3=str1 + str2; str3.display(); void display(); String operator +(String s); } 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 CONVERSION Conversion 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 – 7 DERIVED CLASS AND INHERITANCE
DERIVED CLASS AND BASE CLASS A base class is a class from which other classes are derived. And a derived class can inherit members from a base class. DERIVED CLASS CONSTRUCTORS When 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> void print() class SuperA { cout<< “I am derived class’s function\n”; { public: SuperA :: print(); void print() } { cout<< “I am a Base class’s function\n”; } }; }; void main() class SubA : public SuperA { SubA a; a.print(); } { public: 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. 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:

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
#include<iostrem.h> Class base { protected: int a, b, c; public: void get1(); void put1(); }; class derived : public base { int e, f; public: void get2(); void put2(); }; void base :: get1() 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(); }; (ii) Multiple Inheritance: - A derived class more than one base classes. #include<iostream.h> { 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(); } 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(); }

}; void xyz :: getdata() class xyz { cout<<”Enter the element”; cin>>x>>y; } { protected: void xyz :: putdata() int x, y; { cout<<”x=”<<x<<endl; cout<<”y=”<<y; } public: void abc :: getdata1() void getdata(); void putdata(); { cout<<”Enter the element”; cin>>a>>b; } }; void abc :: putdata1() class abc { cout<<”a=”<<a<<endl; cout<<”b=”<<b; } { protected: void kbc :: getdata2() int a, b; { cout<<”Enter the element”; cin>>k>>b; } public: void kbc :: putdata2() void getdata1(); void putdata1(); { cout<<”k=”<<k<<endl; cout<<”b=”<<b; } }; void main() class kbc: public xyz, public abc { kbc yy; yy.getdata(); yy.getdata1(); { int k, b; yy.getdata2(); yy.putdata(); yy.putdata1(); public: yy.putdata2(); void getdata2(); void 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> void get3(); void put3(); class a }; { protected: void a :: get1() int aa; { cout<<”Enter the element”; cin>>aa; } public: void a :: put1() void get1(); void put1(); { cout<<”aa=”<<aa; } }; void b :: get2(); class b : public a { cout<<”Enter the element”; cin>>bb; } { protected: void b :: put2() int bb; { cout<<”bb=”<<bb; } public: void c:: get3() void get2(); void put2(); { cout<<”Enter the element”; cin>>cc; } }; void c ::put3() class c : public b { cout<<”cc=”<<cc; } { int cc; void main() public: { c yy; yy.get1(); yy.get2(); yy.get3();

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
yy.put1(); yy.put2(); yy.put3(); } (iv) Hybrid Inheritance: - An inheritance has characteristics of more than one inheritance, called Hybrid inheritance. #include<iostream.h> } class a void a :: get1() { protected: { cout<<”Enter the element”; cin>>x>>y; } int x, y; void a :: put1() public: { cout<<”x=”<<x<<”y=”<<y; } void get1(); void put1(); void b :: get2() }; { cout<<”Enter the element”; cin>>a>>b; } class b: public a void b :: put2() { protected: { cout<<”a=”<<a<<”b=”<<b; } int a, b; void d :: get3() public: { cout<<”Enter the element”; cin>>p>>q; } void get2(); void put2(); void d :: put3() }; { cout<<”p=”<<p<<”q=”<<q; } class d void c :: get4() { protected: { cout<<”Enter the element”; cin>>k>>b; int p, q; } public: void c :: put4() void get3(); void put3(); { cout<<”k=”<<k<<”b=”<<b; }; } class c : public b, public d void main() { int k, b; { c yy; yy.get1(); yy.get2(); yy.get3(); yy.get4(); public: yy.put1(); yy.put2(); yy.put3(); yy.put4(); void get4(); void put4(); } (v) Hierarchical Inheritance: - An Hierarchical inheritance begins with root class and expends level to level.

CHAPTER – 8 POINTERS
ADDRESSES 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 ARRAYS Characteristics 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.

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
#include<iostream.h> cout<<str; cout<<str[5]; void main() str++; cout<<str; { char *str = “I am a string”; } Strings as Function Arguments: - The following program shows a string being used as a function argument. #include<iostream.h> void main() void display(char *ptr) { char *str[6] = “I am a String”; display(str); { cout<<ptr; cout<<ptr[5]; } } 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> for(int i=0; I,6; i++) void main() { cout<<str[i]<< “\n”; } { char *str[6] = {“kanak”, “vinay”, “uttam”, “ashish”, } “vinod”, “arun”}; MEMORY MANAGEMENT USING NEW AND DELETE OPERATOR new: - 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 – 9 VIRTUAL FUNCTIONS
POLYMORPHISM It 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 argumentstype. This information, viz. number of arguments types is known to the compiler at the compile time itself.

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
2.
Therefore, the selection of the appropriate function made the compile time only. This is known as early binding or static binding. 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 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> { cout<<”Enter the value for x and y”; cin>>x>>y; } class xyz void xyz :: putdata() { protected: { cout<<”x=”<<x<<endl; cout<<”y=”<<y; } int x, y; void abc :: getdata() public: { cout<<”Enter the value for a and b”; cin>>a>>b; } virtual void getdata(); virtual void putdata(); void abc :: putdata() }; { cout<<”a=”<<a<<endl; cout<<”b=”<<b; } class abc : public xyz void main() { int a, b; { xyz aa, *ptr; abc bb; ptr=&aa; ptrgetdata(); public: ptrputdata(); ptr=&bb; ptrgetdata(); void getdata(); void putdata(); ptrputdata(); }; } void xyz :: getdata() 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> abc() class xyz { A=5; B=10; } { Public: void display(); Virtual void display() = 0; }; }; void abc :: display() class abc : public xyz { cout<<”a=”<<a<<endl; cout<<”b=”<<b; } { private: int a, b; void main() Public: { 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> void abc :: putdata() class abc { cout<<”c=”<<c; } { static int c; int m; void main() public: { abc xx, yy, zz; xx.putdata(); yy.putdata(); void getdata(int); void putdata(); zz.putdata(); xx.getdata(17); yy.getdata(70); }; zz.getdata(101); xx.putdata(); yy.putdata(); void abc :: getdata() zz.putdata(); { M=x; C++; } } Output: C=0 C=0 C=0 C=3 C=3 C=3 Static 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> void abc :: putdata() class abc { Cout<<”c=”<<c; } { int c; void abc :: cal() static int k; { Cout<<”k=”<<k; } public: int abc :: k; void getdata(); void putdata(); void main() static void cal(); { abc xx, yy; xx.getdata(); yy.getdata(); }; xx.putdata(); yy.putdata(); abc :: cal(); void abc :: getdata() } { C=++k; } 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.

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
 Friend function can be friend of one class and more than one class. Friend Function Demonstration: - Example (1): #include<iostrem.h> class xyz #include<conio.h> { private: int x,y; class xyz public: { private: int a,b; void getxyz( ); void putxyz( ); public: friend void sum(xyz,abc); void getdata( ); void putdata( ); }; friend void sum(abc); void xyz :: getxyz( ) }; { cout<<”Enter Two Integers”; cin>>x>>y; } void xyz :: getdata( ) void xyz :: putxyz( ) { cout<<”Enter Two Integers”; cin>>a>>b; } { cout<<”x=”<<x<<”y=”<<y; } void xyz :: putdata( ) void abc :: getabc( ) { cout<<”a=”<<a<<”b=”<<b; } { cout<<”Enter Two Integers”; cin>>a>>b; } void sum(abc xx) void abc :: putabc( ) { int z; z=xx.a+xx.b; { cout<<”a=”<<a<<”b=”<<b; } cout<<”Sum=”<<z; void sum(xyz xx, abc kk) } { int m,n; m=xx.x+kk.a; n=xx.y+kk.b; void main( ) cout<<”m=”<<m<<”n=”<<n; { xyz kk; kk.getdata( ); } kk.putdata( ); sum(kk); getch( ); void main( ) } { xyz cc; abc ll; cc.getxyz( ); Example(2) – cc.putxyz( ); ll.getabc( ); #include<iostream.h> ll.putabc( ); sum(cc,ll); getch( ); #include<conio.h> } class abc; MACROS AND INLINE FUNCTION Macros: - 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 STREAMS
STREAM 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 HIERARCHY HEADER 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.

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
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. 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 file ifstream file_in(“test.txt”); //create file for input file_in.getline (arr, 80); //read a line of text cout<<arr; //display the read line } FILE HANDLING To carry out – cout Stream operator cin read and write operation from console to main memory ifstream ofstream classes fstream i) 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> char ch[n]; ifstream input (“xyz”); #include<conio.h> while (input) #include<fstream.h> { input.getline (ch, n); void main() cout<<ch; { ofstream kk (“xyz”); kk<<”Patna”; } kk<<”Ranchi”; kk<<”Kolkata”; input.close(); kk<<”Delhi”; kk<<”Mumbai”; } kk.close(); int n = 80; Program to create more than one text file with single stream object #include<iostream.h> void main() #include<conio.h> { ofstream kk; kk.open (“City”); #include<ifstrem.h> kk<<”Patna”; kk<<”Ranchi”; kk<<”Kolkata”;

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
kk<<”Delhi”; kk<<”Mumbai”; kk.close(); { ll.getline (ch, n); cout<<ch; kk.open (“Rajdhani”); kk<<”Bihar”; kk<<”Jharkhand”; } kk<<”West Bengal”; kk<<”New Delhi”; ll.close(); ll.open(“Rajdhani”); kk<<”Maharastra”; while(ll) kk.close(); ifstream ll; int n = 80; char ch; ll.open { ll.getline(ch, n); cout<<ch; (“City”); } while(ll) File Method of writing and reading (i) Text file Line by line (ii) Sequential Char by char (iii) Object By block Binary read/write operations with file Function 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> { ff.put(nm[i]); } #include<conio.h> ff.seekg(0); /*To reset the get pointer at beginning void main() of file*/ { char nm[15]; cout<<”Enter the string”; char ch; cin>>nm; int length = strlen(nm); { ff.get(ch); cout<<ch; } fstream ff; ff.open (“abc”, ios :: in|ios :: out); getch(); for(int i=0;i<length;i++) } 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> cout<<”Designation”<<design<<endl; #include<conio.h> cout<<”Employee salary”<<sal; class emp } { int empno, sal; char desig[15], name[20]; void main() public: { emp ee[10]; fstream ff; void getdata(); void putdata(); ff.open(“employee”, ios :: in|ios :: out); }; for(int i=0;i<10;i++) void emp :: getdata() { ee[i].getdata(); { cout<<”Enter emp no”; cin>>empno; ff.write((char*) & ee[i], size of (ee[i])); cout<<”Enter salary”; cin>>sal; } cout<<”Enter Designation”; cin>>design; for(i=0;i<10;i++) cout<<”Enter employee name”; cin>>name; { ff.read((char*) & ee[i], size of (ee[i])); } ee[i].putdata(); void emp :: putdata() } { cout<<”Employee Name”<<name<<endl; ff.close(); getch(); cout<<”Employee No”<<empno<<endl; } File Streams: argc=3  creation & string of text file }  creation & string a file sequentially void main(int argc, char *argv[]) Command line argument { int a[6]={9,10,11,12,13,14}; C:\>KBC odd Even int i; ofstream ff, ff’; ff.open(“argv[1]”,ios::out); Name of source file(c++ file name) ff’.open(“argv[2]”,ios::out); void main(int argc, char *argv[]) if(argc!=3) { { exit(0) } argv[0]=KBC for(j=0;j<6;j++) argv[1]=odd { if(a[j]%2==0) argv[2]=Even

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
ff<<a[i]; else ff’<<a[j]; } } ffclose(); ff’close();

CHAPTER – 11 EXCEPTION HANDLING
Exception handling provides a way of transferring control and information to an unspecified caller that has expressed willingness to handle exceptions of a given type. Exception of arbitrary types can be ‘throw and catch ‘and set of exceptions a function may throw can be specified. Exception handling handles run time errors. Mainly generated the run time errors are as follows:• logical:- poor understanding of given problem and procedure of solution. • Syntax :- poor understanding of programming language. • Exception:- arises when program executed due to: Illegal arithmetic expression like digit divided by zero.  Array overflow.  Array index out of bound.  Incompatible assignment etc. It mechanism transfers control and information from a point of exception in a program to an exception handler associated with the tryblock. An exception handler will invoked only by a thrown expression in the code executed by the handler’s try-block. C++ provides following keywords to deal with exception. These are:• Try: - try is basically, a block where exception is generated. • Throw: - when exception is generated, it must be ‘throw’ is used to throw the exception. ‘throw’ is used in ‘try’ block. • Catch: - catch () is also a block, where exception handler statements are defined. It is basically a function & accepts exception that is thrown by throw. # program to demo. Exception handling void main() { int b,c; cout<<”enter value of b & c”; cin>>b>>c; try{ if(c==0) throw c; else cout<<b/c; } catch(int k) { cout<<”exception caught”<<k; } } # program to demo. Exception handling with multiple catch void test(int) if(k==3) void main() { throw 9; } { int n; cout<<”enter the no.s[1,2 or 3]”; } cin>>n; test(n); catch(char nm) } { cout<<”exception caught”<<nm; } void test(int k) catch(int m) { try { { cout<<”exception caught”<< m; } if(k==1) catch(float n) { throw ‘x’;} { cout<<”exception caught”<<n; } if(k==2) } { throw 12.3; }

CHAPTER – 12 CLASS LIBRARIES
Class Libraries: - C++ provides a library of data structures. Standard C++ includes its own built-in container class library. String Class: - The string class stores the string as a character array and it includes a field that stores the size of the array. In order to use this class we need to place the statement: #include<string> Constructors String() It creates an empty class. Syntax: string s1; String s2(“kanak”) Initialize the string with a character array. String s1(s2) Initialize a string (say s1) from another string (say s2) using the statement String s1(6, ‘m’) Initialize a string as a repeated sequence of characters using the statement Function

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
Assign() 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>; Program to demo: #include<stack> #include <vector> int main() cout<<s.top()<<endl; { //Now pop them off Stack<int, vector<int> s; //Make a stack using a vector s.pop(); container cout<<s.top()<<endl; //Push a couple of values on the stack s.pop(); s.push(1); return 0; s.push(2); } Member Function Bool empty() Returns true if the stack is empty, otherwise false Void pop() Removes the item at the top of the stack Void push(const value_type& x) Pushes x onto the stack Int size() Return the number of elements in the stack Stack_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 Function Bool empty() Returns true if size is zero List_type back() Returns a copy of the back element List_type front() Returns a copy of the front element Void merge(anotherlist) Merges in the contents of another list Void pop_front(element) Removes the front element Void push_front(element) Adds an element at the front Void push_rear(element) Adds an element at the back Void remove(element) Removes ALL occurrences of the element Void reverse() Reverses the order of the list Int size() Gets the current number of lists element Void sort() Sorts the list elements (ascending order) Void swap(anotherlist) Swaps this list’s contents with the other list Queue 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 Function Queue_type back() Returns the item at the back of the queue. Bool empty() Returns true if the queue is empty, otherwise false Queue_type front() Returns the item at the front of the queue. Void pop () Removes the item at the front of the queue Void push (queue_type x)) Pushes x onto the back of the queue. Int size() Returns the number of elements on the queue Microsoft 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 – 13 ADVANCE CLASSES
TEMPLATES Template 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) else { if (a>b) return b; return a; } 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.

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
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 templates template<class t> void xyz::display() class xyz { cout<<”a=”<<a; cout<<”b=”<<b; { t a,b; } public: void main() xyz(t x,t y) { xyz<int,int>aa(5,7); { a=x; b=y; xyz<float,float>bb(13.2,15.7); } aa.display; bb.display; void display(); } }; Program to demo class templates with two parameters templates<class t1,class t2> void xyz::display() class xyz { cout<<”a=”<<a; cout<<”b=”<<b; { t1=a; t2=b; } public: void main() xyz(t1=x,t2=y) { xyz<int,float>aa(5,7.3); { a=x; b=y; xyz<int,char>bb(6,’v’); } aa.display(); bb.display(); void display(); } }; Program to demo. function template template<class t> template<class t1, class t2> void exchange(t x,t y) void sum(t1 x,t2 y) { t z; z=x; x=y; y=z; { t2 z; z=x+y; cout<<”x=”<<x<<”y=”<<y; cout<<”sum=”<<z; } } void main(); void main() { int a,b; float j,k; cout<<”Enter two integers”; { int a; float b; cout<<”Enter integer”; cin>>a>>b; exchange(a,b); cin>>a; cout<<”Enter float”; cout<<”Enter two floats”; cin>>b; sum(a,b); cin>>j>>k; exchange(j,k); } } Member function template template<class t> { cout<<”Enter two numbers”; class xyz cin>>a>>b; { t a,b; }template<classt’> public: void xyz<t>::putdata() void getdata(); void putdata(); { cout<<”a=”<<a; cout<<”b=”<<b; } }; void main() template<class t> { xyz pp; pp.getdata(); pp.putdata(); } void xyz<t>::getdata() 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> else T compare (T a, T b) return b; { if (a>b) } return a; 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>

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
void print (T a) Float y = 10.56; { cout<<”all data types\n”; } Print(x); //function called with int data type void print(float a) //overriding template function Print (y); //function called with float data type { cout<<”float data type\n”; } Print (“Hello”); //function called with string data type Void main() } { int x = 10; Containers and Nested Class: - A container class is a class that operates on a collection of zero or more objects of a particular type. 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> { size = m; v = new T[size]; Template <class T> } Class Vector Vector (T *a) //create a vector from an array { T *v; //type T vector { for(int i=0; i<size; i++) int size; { v[i] = a[i]; } Public: } Vector (int m) //create a vector of size m }; 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 ChNode *head; { Protected: Public: Class ChNode //Hidden, protected node class ChList(); ~ChList(); int AddtoFront (char &c); { public: int RmvHead (char &c); int IsEmpty(); int IsFull(); Char data; ChNode *next; ChNode(); }; 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 voiletion class xyz void get2(); voidput2(); { int a,b; }; protected: void main() int x,y; { public: ABC xx; -------(i) xx.a=15;-------(ii) int z; void get1(); void put1(); xx.z=13;-------(iii) xx.put1();------(iv) }; xx.y=21;-------(v) xx.J=25;-------(vi) class ABC:public xyz xx.put2();------(vii) { int J,K; } public: (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);

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++
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 =. else Example--> string s1,s2; { s2=”ABC” -----s1=s2 } (ii) Comparison operator(<,<=,>,>=) (iii) Addition operator(+) for concatenation Example--> string s1,s2; Example--> string s1,s2,s3; s1=”ABC”; s1=”XYZ”; s2=”KBC”; s2=”PVT Ltd”; if(s1<s2) 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 :while(i<6) Datatype *pointer variable; { cout<<*ptr; Example  ptr++; int *ptr, a; i++; a=15; } ptr=&a; String--> best example of Array(character) cout<<*ptr; *If we have to work with string ,then we use character array Array handling through pointer :to hold and manipulate the string. int s[6] ={1,3,5,7,2,4}; Example- char *string 1=”How many bytes are allocated for int*ptr,1; short int”; ptr=&s[0]; cout<<string1; i=0; cout<<string1[0]; Memory management using new and delete operators (v)

NOTES BY –BALJEET SINGH SINWAR

28

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

28

Sign up to vote on this title
UsefulNot useful