Object Oriented Programming Through C++

  • June 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Object Oriented Programming Through C++ as PDF for free.

More details

  • Words: 14,904
  • Pages: 28
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 (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 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

Meaning Prints a carriage return. Prints a horizontal tab.

\v

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 [Size] Declaration of Double Dimension Array: Syntax: Data type [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> a>>b a=a>>b /= a/=b a=a/b >>> a>>>b a=a>>>b %= a%=b a=a%b << a<
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=”<> 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 getch( ); #include } 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>>b; *q=t; exchange(&a,&b); cout<<”a=”<<*p<<endl; cout<<”a=”< } #include Void sum(int, int) Void sum(int, int); { Void sum(float, float); int z; Void main( ) z=x+y; { int x,y; cout<<”Sum=”<>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 Xyz( ) #include { 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 main( ) { Xyz xx; xx.show( ); cout<<”Sum=”<<xx.sum( ); }

}; Void xyz :: show( ) { Cout<<”x=”<<x<<endl; Cout<<”y=”<
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 cout<<”local=”<
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 #include 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=”< Multiple Object #include { cout<<”Enter Two Integers”; Cin>>a>>b;} #include Void xyz :: putdata( ) Class xyz { cout<<”a=”< Array Type object #include Void xyz :: putdata( ) #include { cout<<”a=”<>a>>b;} Case IV => Pointer type object #include { cout<<”Enter Two Integers”; cin>>a>>b;} #include Void xyz :: putdata( ) Class xyz { cout<<”a=”< 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 class emp

NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++ {

private: int number;

int age;

public:

Cout<< “age=”; Cin>>age; } Void displaydate() { cout<< “\n number=”<
void getdata() void displaydate() }; Void getdata() { cout<< “number=”; Cin rel="nofollow">>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 }; #include void xyz :: show( ) class xyz { cout<<”a=”< { private: #include 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=”<
}; Overloaded Constructor Demonstration: #include Void show( ); #include }; class xyz Void xyz :: show( ) { private: int a,b; { Cout<<”a=”< 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< Void show( ); #include }; class xyz Void xyz :: show( ) { private: int a,b; { Cout<<”a=”< } 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 Void show( ); #include }; class xyz Void xyz :: show( ) { private: { cout<<”x=”<<x<<endl; cout<<”y=”<
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 (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 { X=5; Void xyz :: show() #include Y=10; } { cout<<”x=”<<x<<endl; class xyz Void show(); cout<<”y=”< { X=5; Void xyz :: show() #include Y=10; } { cout<<”x=”<<x<<endl; class xyz Void show(); cout<<”y=”< { X=5; Void xyz :: show() #include Y=10; } { cout<<”x=”<<x<<endl; class xyz Void show(); cout<<”y=”<
NOTES BY –BALJEET SINGH SINWAR

28

OBJECT ORIENTED PROGRAMMING THROUGH C++ #include }; #include 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=”< }; #include 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=”< }; #include 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=”< }; #include 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=”< }; #include 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=”<) operator #include 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 class man { private: int age; public: void getdata(); void operator < (man p) { if (age 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 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 class xyz { private: int a[3]; public: void putdata(); Friend istream << (istream, xyz); }; void xyz :: putdata() { for(int i=0;i<3;i++) { cout< class xyz { private: int x, y; public: void getdata(); void putdata();

NOTES BY –BALJEET SINGH SINWAR

} }; 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>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<>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=”<
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 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 }; #include<string.h> void String :: display() class String { cout<
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 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>: Case I – If the association between base and derived class is public:

NOTES BY –BALJEET SINGH SINWAR

28

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

{ cout<<”Enter the element”; cin>>a>>b>>c; } void base :: put1() { cout<<”a=”<>e>>f; } void derived :: put2() { cout<<”e=”<<e<<endl; cout<<”f=”<>a>>b>>c;} void base :: put1() { cout<<”a=”<>e>>f; } void derived :: put2() { cout<<”e=”<<e<<endl; cout<<”f=”<
}; 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=”<>a>>b; } }; void abc :: putdata1() class abc { cout<<”a=”<>k>>b; } public: void kbc :: putdata2() void getdata1(); void putdata1(); { cout<<”k=”< 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=”<>bb; } { protected: void b :: put2() int bb; { cout<<”bb=”<>cc; } }; void c ::put3() class c : public b { cout<<”cc=”<
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 } class a void a :: get1() { protected: { cout<<”Enter the element”; cin>>x>>y; } int x, y; void a :: put1() public: { cout<<”x=”<<x<<”y=”<>a>>b; } class b: public a void b :: put2() { protected: { cout<<”a=”<>p>>q; } void get2(); void put2(); void d :: put3() }; { cout<<”p=”<>k>>b; int p, q; } public: void c :: put4() void get3(); void put3(); { cout<<”k=”<
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 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 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 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 void main() void display(char *ptr) { char *str[6] = “I am a String”; display(str); { cout< 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 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 { cout<<”Enter the value for x and y”; cin>>x>>y; } class xyz void xyz :: putdata() { protected: { cout<<”x=”<<x<<endl; cout<<”y=”<>a>>b; } virtual void getdata(); virtual void putdata(); void abc :: putdata() }; { cout<<”a=”< abc() class xyz { A=5; B=10; } { Public: void display(); Virtual void display() = 0; }; }; void abc :: display() class abc : public xyz { cout<<”a=”< void abc :: putdata() class abc { cout<<”c=”< void abc :: putdata() class abc { Cout<<”c=”<
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 class xyz #include { 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=”<>a>>b; } void sum(abc xx) void abc :: putabc( ) { int z; z=xx.a+xx.b; { cout<<”a=”< ll.putabc( ); sum(cc,ll); getch( ); #include } 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 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< char ch[n]; ifstream input (“xyz”); #include while (input) #include { input.getline (ch, n); void main() cout< void main() #include { ofstream kk; kk.open (“City”); #include 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< { ff.put(nm[i]); } #include 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< cout<<”Designation”<<design<<endl; #include 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”<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<
} ffclose(); ff’close();

else ff’<
}

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 rel="nofollow">>b>>c; try{ if(c==0) throw c; else cout<>n; test(n); catch(char nm) } { cout<<”exception caught”<
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 int main() cout<<s.top()<<endl; { //Now pop them off Stack 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 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 void xyz::display() class xyz { cout<<”a=”<aa(5,7); { a=x; b=y; xyzbb(13.2,15.7); } aa.display; bb.display; void display(); } }; Program to demo class templates with two parameters templates void xyz::display() class xyz { cout<<”a=”<aa(5,7.3); { a=x; b=y; xyzbb(6,’v’); } aa.display(); bb.display(); void display(); } }; Program to demo. function template template template 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=”<>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 { cout<<”Enter two numbers”; class xyz cin>>a>>b; { t a,b; }template public: void xyz::putdata() void getdata(); void putdata(); { cout<<”a=”< { xyz pp; pp.getdata(); pp.putdata(); } void xyz::getdata() Template Function: - A template function is declared as follows: template 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 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 Template

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. then, this object will contain a vector of integer values. Program to demo Container class: #include { size = m; v = new T[size]; Template } 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 }; 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++ (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 =. 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

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

Related Documents