What is C++? C++ also allows us to create hierarchy related objects. All C programs are also C++ programs with few differences.

Similar documents
PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

C++ INTERVIEW QUESTIONS

13 Classes & Objects with Constructors/Destructors

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

The C Programming Language course syllabus associate level

Basics of I/O Streams and File I/O

Object Oriented Programming With C++(10CS36) Question Bank. UNIT 1: Introduction to C++

Subject Name: Object Oriented Programming in C++ Subject Code:

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

El Dorado Union High School District Educational Services

C++ Programming Language

Glossary of Object Oriented Terms

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

Java Interview Questions and Answers

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

C++ Input/Output: Streams

Object Oriented Software Design II

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

ALLIED PAPER : DISCRETE MATHEMATICS (for B.Sc. Computer Technology & B.Sc. Multimedia and Web Technology)

Member Functions of the istream Class

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

Java (12 Weeks) Introduction to Java Programming Language

Chapter 2: Elements of Java

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Chapter 5 Names, Bindings, Type Checking, and Scopes

Illustration 1: Diagram of program function and data flow

Sources: On the Web: Slides will be available on:

BCS2B02: OOP Concepts and Data Structures Using C++

Syllabus OBJECT ORIENTED PROGRAMMING C++

Course notes Standard C++ programming

C++ Language Tutorial

5 Arrays and Pointers

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Module 816. File Management in C. M. Campbell 1993 Deakin University

Course Title: Software Development

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Database Programming with PL/SQL: Learning Objectives

Chapter 13 Storage classes

C Interview Questions

Informatica e Sistemi in Tempo Reale

C++FA 5.1 PRACTICE MID-TERM EXAM

I PUC - Computer Science. Practical s Syllabus. Contents

10CS35: Data Structures Using C

Chapter One Introduction to Programming

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Chapter 5 Functions. Introducing Functions

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

Binary storage of graphs and related data

Object Oriented Software Design

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

WORKSPACE WEB DEVELOPMENT & OUTSOURCING TRAINING CENTER

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

/* File: blkcopy.c. size_t n

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Curriculum Map. Discipline: Computer Science Course: C++

Object Oriented Software Design

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Lab 2 - CMPS 1043, Computer Science I Introduction to File Input/Output (I/O) Projects and Solutions (C++)

Basic Object-Oriented Programming in Java

Moving from CS 61A Scheme to CS 61B Java

arrays C Programming Language - Arrays

Computer Programming I

Compiler Construction

System Calls and Standard I/O

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

AP Computer Science Java Subset

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

MISRA-C:2012 Standards Model Summary for C / C++

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

System Calls Related to File Manipulation

Java CPD (I) Frans Coenen Department of Computer Science

1 Abstract Data Types Information Hiding

Fundamentals of Java Programming

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

Class XII (Theory) C++

SUBJECT :- COMPUTER SCIENCE (083) CLASS XII. Unit-Wise Marks and Period Distribution

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Test #4 November 20, True or False (2 points each)

Introduction to Java

UML for C# Modeling Basics

C Compiler Targeting the Java Virtual Machine

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

PL / SQL Basics. Chapter 3

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Computer Programming C++ Classes and Objects 15 th Lecture

Semantic Analysis: Types and Type Checking

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

COMPUTER SCIENCE 1999 (Delhi Board)

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

PROBLEMS (Cap. 4 - Istruzioni macchina)

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Parameter Passing. Parameter Passing. Parameter Passing Modes in Fortran. Parameter Passing Modes in C

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Transcription:

What is C++? 1 Object oriented programming languages. Initially named as C with classes. C++ was developed at AT & T Bell Labs. C++ is superset of C. Three important facilities are added onto C. Classes functions overloading operator overloading C++ also allows us to create hierarchy related objects. All C programs are also C++ programs with few differences. Input / Output # include <iostream.h> <iostream.h> contains declaration of objects used in input/output statements (Naming conventions of header files may vary such as iostream.hpp. cin and cout are predefined objects in <iostream.h> for single interface. cin >> number is an input statement and causes program to wait for user to type in a number. The identifier cin is a predefined object in C++ that corresponds to the standard input stream (keyboard). >> is known as extraction or get from operator that extracts or gets value from keyboard. This corresponds to scanf( ). The statement cout << number causes program to put the value of number on standard output stream (screen in this case). The operator << is called put to operator. Operators <<, >> are also called bit wise operators. printf ( ) and scanf ( ) can still be used but include header file <stdio.h>. Cascading of I/O operators In the statement cin >> num1 >> num2, the values are assigned from left to right. In the statement cout << sum= << sum << \n, first sends the string sum= to cout and then sends the value of sum and finally it to sends the new line char. Comments In C In C ++ /* comments */ /* comments for multiple lines */ // single comment line and can t be inserted within the text of a rogram. Structure of C++ program Include files Class declaration Class functions definitions Main function program Data types of C++ User_ defined Built_in Derived type structure int array union char function class float pointer enumerated double void

2 User Defined DT struct and union are same as in C used for defining static and dynamic records. enumerated Data Type differ slightly in C++ enum shape {circle, square, triangle; Here circle =0, square =1 and triangle =2 are automatically assigned. Here shape becomes new type name and can be used to declare new variables such as shape ellipse; More examples: enum color {red, blue=4, green=8; enum color {red, blue=1, green=2. Here red = 0 enum color {red=5, blues=6, green=7; enum {off, on {without name. We can declare int switch1=off; int switch2=on; Variable declaration In C, all variables are declared { e.g., int x, y; float p, q; at the beginning of the scope. In C++, the declaration of a variable can be anywhere in the scope but before the first use. It makes program easier to understand. Only disadvantage is that we can t see all variables at a glance used in the scope. Additional feature of C++ is dynamic or run time initialization {e.g., int x =3. Constants C++ constants are to be initialized as: const int size =10; char name[size]; In C, the primitive #define is used to create constants. enum { X, Y, Z; defines X, Y, Z as integer constants with values 0,1,2 respectively and is equivalent to defining const X = 0; const Y = 1; const Z = 2; enum { X=10, Y=20, Z=15; is equivalent to defining const X = 10; const Y = 20; const Z = 15; Only integer constants can be defined using enum data type. Pointers Available in C & C++ int *i; i = & x; // address of x is assigned to i *i = 50; /* 50 value assigned to a location pointed out by i through indirection. */ Void (Available in C & C++ both) to specify the return type of a function that does not return any value to indicate empty argument list to a function to declare generic pointers in C++ void *p ; int *i ; p = i ; // assigns i pointer to void pointer p i = p ; // not allowed void pointer p can be assigned a pointer value of any basic data types. void pointer may not be dereferenced Reference variables C++ introduces a new kind of variable called reference variable which provides an alias for previously defined variable. General format is data_type &ref_var = var_name

3 float total = 50; float &sum = total; cout << sum; sum and total both are same locations. Major application is in passing arguments to functions [call by reference] void func1 (int &x) { x = x + 10; main ( ) { int m = 10; f (m); Scope resolution operator Declaration of variable in an inner block hides a declaration of the same variable in an outer block. Here :: is a scope resolution operator. { int x = 10; // x is a global variable { int x =1; // x is a local variable :: x = :: x +1; // ::x refers to global variable ; Memory management with pointers Along with malloc() & calloc(), C++ also defines two unary operators new and delete. These operate memory on the free store (also called free store operators). Life time of an object is directly under our control & unrelated to a block structure. Object created with new will remain until destroyed using delete. pointer_var = new data_type; (Including user defined) int *p; float *q; int *p = new int; : float *q = new float; p = new int; q = new float; int *p = new int [3]; or int *p; p = new int[3]; creates memory space for an array of 3 integers where *p refers to first element, *(p+1) refers to 2nd element, and *(p+2) refers to 3rd element. int *p[3]; an array of pointers pointing to locations having integer values. Memory is allocated by using *p = new int; and elements are referenced as *p[0], *p[1] and *p[2]. delete p or delete [] p. In case of insufficient memory, new returns null pointer Advantages over malloc( ) Automatically computes the size of data Object possible to initialize object while creating memory space these can be overloaded Functions in C++ The function int main ( ) returns a value of type int to the operating system. Here int is optional as it takes type by default. If int is specified before main ( ) then return statement is used for termination. Normal convention is that if 0 is returned then the program ran successfully while non zero value means that there is some problem.

4 Function prototyping must be given in C++ which gives compiler the details such as number, type of arguments and return type { e.g., float volume (int, float, float). Should preceed a function definition and no need to specify arguments but types are sufficient. In C++, function without arguments can be written as o void display ( ); or void display (void); However in C, ( ) means any number of arguments. In C++ this can be written (open parameter list) such as void do-something ( ) Call by reference In C, parameters are passed by value but in C++, they can be passed as reference or value. Swapping of two integer values C function void swap (int *a, int *b) { int t; t = *a; *a = *b; *b = t; Call : swap(&m,&n) C++ function void swap (int &a, int &b) { int t; t = a; a = b; b = t; Call : swap(m, n) Each argument in function must be declared independently inside the parenthesis. Returning a reference A function can also return a reference int &max (int &x, int &y); { if (x > y) return x; else return y; Call max (a, b) returns a reference to either a or b depending upon the values. This implies that function call can appear on L.H.S in contrast to other programming Languages including such as max ( a, b ) = -1 which assigns -1 to a if a > b else 1 to b. Default Arguments C++ allows a call of function without specifying all its arguments. In such cases default values are specified when function is declared. Default values are always specified from right to left. float amount (float p, int t = 3, float r = 0.15); various calls :- value = amount (5000, 7,.12); value = amount (5000, 7). Here r=0.15 is taken. value = amount (5000); here t = 3 and r = 0.15 Function Overloading Same function name can be used to create variety of tasks. It is called function polymorphism in OOP (Object Oriented Programming) Various declarations: int add (int, int); int add (int, int, int);double add (double, double); double add (int, double); double add (double, int); Various calls: x = add(5,10); x = add(5,10,15); x = add(2.5,10.2); x = add(5,10.9); x = add(5.5,10); Compiler tries to find exact match where types of actual arguments match.

If exact match is not found then it performs internal conversions such as char int; float long ; int float; float int etc. 5 For multiple matches error message is generated such as if we have long sq (long x); double sq (double x); function call sq (10) matches with long and double both, so error message is generated To avoid such situation, sq( ) should be used Inline function Ordinary function are compiled separately and called as and when required. In order to save time/overheads in calling function & returning to called program, a powerful facility is available in C++ Inline function is defined as inline int sq (int x) {return (x *x) and call to this function is same as ordinary function i.e., p = sq (2) Inline function are not called at execution time instead function call is expanded by the body of function. In C, similar effect is achieved by macro definition defined by primitive # define. Here macro processor performs textual substitution shown below: # define rate 1.5 # define tax(x) x * rate; Macro call tax(p + 2) is expanded as {p + 2 * rate which is not the intention. Macro can t have local variables and it does not even define a block. Macro also do not permit parameter checking. C++ solves the drawbacks of C macro with inline function which is small function of one or two lines. Inline modifier lets compiler mark a particular function to be expended rather than compiled. C++ compiler may ignore your request if your function is too long. Advantage of inline function is that they can help you write well-designed, modular programs that remain efficient at the code level. Definition is given as follows: #define rate 1.5 inline float tax (x) { return (x * rate ) ; Call to this inline function is y = tax(p + 2) which does the intended job incontrast to macro call. Speed benefits of inline functions diminish as the function grows in size Classes and Objects A class is an extension of an idea of structure used in C. A new way of creating and implementing a user defined data type. struct data type can not be treated like built-in type. If we define struct comp {float x; float y; c1, c2, c3 then, c3= c1 +c2 is not possible. Another important limitation of structures is that they do not permit data hiding. Members of a structure can be directly accessed anywhere within their scope. C++ attempts to bring user defined types as close as possible to the built in data types and also provides a facility to hide the data which is an important concept of OOP. Class It is a data type in C++ which holds data and functions. It has two parts: Class declaration (same as structure declaration) Class function definition (describes how the functions are implement) General form of class

6 class class_name { private: optional variable_declarations; function_declarations; public: variable_declarations; function_declarations; Here variables are data members and functions are member functions. Usually grouped under two sections Private & Public. Private members can be accessed only within the class (data hiding) and not visible / accessible outside the class. Public members can be accessed from outside the class also. Only member functions (private/public) can have access to the private members (data & functions). Binding of data and functions together into a single class_type variable is called Encapsulation. For example: { private: int num i ; float cost ; public: get_data (int a, float b); void put data(void) General convention for class is to make the value (variable members) part of the data type private and make the functions public. Actual function definitions can appear within the class or outside the class, anywhere in the program (valid for public functions). Objects can be created by simple declaration similar to variable: item x,y,z; Defining member functions Inside the class : { int num; float cost; public: void gdata (int a, float b) { num = a; cost = b; ; void putdata (void) { cout << num << \n ; cout << cost << \n ; When a function is defined inside a class it is treated as an inline function that means only small functions are defined insides the class. Outside the class : return_type class_name :: fun_name (arg list dec) { body Class_name tells compiler that fun-name belongs to which class { int num; float cost; public: void gdata (int a, float b); void putdata (void); void item :: gdata (int a, float b) can access private data { num = a; cost = b; ; void item :: putdata (void) { cout << num << \n ; cout << cost << \n ; Making an outside function inline

Good practice is to define the member functions outside the class. We can also define such functions as inline by just using qualifier inline. { int num; float cost; public: void getdata (int a, float b); ; inline void item :: getdata (int a, float b) { num = a; cost = b; Accessing class members item x; x.gdata (10,7.5); x.putdata ( ) ; // x.num = 10 is illegal 7 Object of a class can call member function or member variables if declared in public section by using dot operator as x.gdata (10,7.5). Note that objects communicate by sending & receiving messages through the member functions. Nesting of member functions Member function can be called by using its name inside another member function of the same class. This is called nesting of member function. Private member function Some situation may require to hide member functions also. For example, deletion of account in customer file, providing increment. class sample { int m; void get (void) {...; public: void update (void); void sample :: update (void) { get ( ) is legal as public function can access private function/data. Memory Allocation for Object When class is declared, member functions are created and placed in the memory space only once. When an object is declared as a specific class type, same member functions are used and no separate allocation is done. But space for member variables is allocated for each object. Static member variables Used to maintain values common to entire class. Each static member variable must be defined before the class definition.(as they are stored separately rather than as a part of an objects) All objects share same copy of static variable. They are associated with class rather than object, so called class variables. They are visible only within the class but its lifetime is the entire program. It is initialized to zero when the first object of its class is created. { static int count;

int num; public : void getdata (int a ){ num = a; count ++; void getcount (void ) { cout << count: ; cout << count << \n ; int item :: count; // count of item is defined main ( ) { item a, b, c; a.getdata (10); b.getdata (20); c.getdata (30); a.getcount(); Output of above program: count:3 8 Static member functions Static function can have access to static members (functions / variables ) declared in the same class. Static member function can be called using the class name (instead of its objects). item :: static_fun is a call to static function and t1. fun_name is call to ordinary function where t1 is an object. Arrays of objects item a[10]; a[i]. getdata; a[i]. getcount; Objects as arguments in the Function There are two ways of passing object as a parameter. call by value : A copy of the entire object is passed to the function. call by reference: Only the address of the object is transferred to the function. Object can be passed to member functions of the same class / to a non member function. { int num; public : void getdata (int a ) { num = a; void add (item s1, item &s2 ) { cout << s1.num + s2.num ; Returning objects Functions can return objects. class complex { float x; float y; public : void inputdata (float r, float i) { x = r; y = i; void show (complex c) { cout << c.x << +i << c.y << \n ; complex sum (complex c1, complex c2) { complex c3; c3.x = c1.x + c2.x; c3.y = c1.y + c2.y; return (c3);

9 main ( ) { complex a, b, c; a. inputdata (3.1, 2.1); b. inputdata (2.8, 3.4); c = sum (a, b) ; cout << c. show ( c) ; Constant Member Function If member function does not alter any data in the class, we may declare it as const member function by appending a function declaration with the qualifier const. void mult (int, int) const ; error message is generated if such function tries to alter the data. Pointers to Members Address of a member (data / function) can be obtained by applying symbol & to a fully qualified class member name. A class using pointer can be declared using the operator ::* with the class name. { int m; public : void show ( ) ; Pointer to the members of a is defined by item ::* Pointer ptr to member m is defined as int item ::* ptr = &item :: m; Here &item :: m means address of m (m is member of ). The pointer ptr defined above can be used to access the member m inside the member functions and not allowed to access outside the class. cout << t.* ptr Or cout << t. m are same. Here t is an object inside a member function. Dereferencing * is used to access a member when we use pointers to both the object and the member. ip = &t; cout << ip * ptr; // displays m.* is used when the object itself is used with the member pointer t.*ptr Note that *ptr is used like a member name Inheritance : Extending classes C++ strongly supports the concept of reusability. Its classes can be reused by creating new classes and reusing the properties of existing. New class can be derived from an old classes. This is called inheritance. Old class is referred to as the base class and the new one is called the derived class. Derived class inherits some or all properties from the base class. Single inheritance : Derived class has only one base class. Multiple inheritance : Derived class with several base classes. Hierarchical inheritance : One class is inherited by more than one classes. Multi level inheritance : Deriving a class from another derived class. Hybrid inheritance : (multilevel and multiple inheritance)

10 Defining derived class General format is: class d-class: visibility-mode base_class {.. Visibility modes : private or public Default visibility mode is private. Private Visibility mode class d_class : private base_class {... Here public members of base_class become private members of the derived class. The public members of base_class can only be accessed by the member functions of the derived class. Object of the derived class can not inherit private members of base class. Public members of base class even can not be accessed by objects of derived class. Public visibility mode class d_class : public base_class {... Public members of base_class become public members of d_class also and thus objects of d_class can access them by dot operator. Note that private members of the b_class are not inherited in both the cases. Derived class can have its own private and public members that extend the capabilities of the existing classes. class B { int a; public: int b; void get_ab ( ); void get_a ( ); void show_a ( ); ; // end of base class B class D : private B { int c; public: void mul ( ) ; void display ( ); ; // end of derived class D class E : public B { int d; public : void add ( ) ; void show ( ) ; ; // End of derived class E The declaration D p declares p to be an object of type class D. Here p can not access members (private or public) of base class B. The declaration E p declares p to be an object of type class E. Here p can access only public members of base class B. Making private members inheritable If private data needs to be inherited by a derived class, then one way is to make them public. But it eliminates the advantage of data hiding. C++ provides alternative visibility modifier called protected mode which serves this purpose of limited inheritance. Protected members are accessible by the member functions of its own class and any class immediately derived from it. class ABC { privates: /* optional, visible to member functions within class */ protected: /* visible to its member functions and immediate derived class */ public: /* visible to all function in the program */

Keywords may appear in any order and in any number of times in the class 11 Protected visibility of inherited members Protected members, when inherited in public mode, it becomes protected in the derived class too and thus ready for further inheritance. Protected members when inherited in private mode becomes private and not available for further inheritance. Declarations for various inheritance Single inheritance class A {... ; class B : public A { ; class C : private A { ; Multiple inheritance class A { ; class B { ; class C : public A, private B { ; Multilevel Inheritance class A {.. ; class B : public A { ; class C : public B { ; class D: public C {.; Hierarchical Inheritance class A {.. ; class B : public A { ; class C : private A { ; class D : public A {.; Hybrid inheritance (combination of multilevel or multiple inheritance Diagram) class A {. ; class B : public A { ; class C : private A{ ; class D : public B, private C { ; Here D (child) inherits from its base (parent) classes which has a common base class A called grand parent. In such situations child inherits from grand parent via two separate paths. Grand parent is sometimes referred to as indirect base class. Such inheritance might pose some problems as all public & protected members of grand parent are inherited into child twice first via parent_1 and again via parent_2. This creates ambiguity and should be avoided. Virtual Base classes Declare ancestor class as a virtual base class (Only one copy of A will be inherited by D) class A { ; class B : virtual public A { ; class C : public virtual A { ; // Order is immaterial class D : public A, public B {...; Abstract class An abstract class is one that is not used to create objects. It can act as a base class to other classes and thus a design concept in program development that provides a base class upon which other classes may be built. Virtual class is taken as abstract class.

Nesting of classes C++ supports another way of inheriting properties of one class into another. Object can be a collection of many other objects i.e., class can contain objects of other classes as its members. class alpha { ; class beta { ; class gamma { alpha a ; beta b ;. gamma p ; p is an object of gamma type which contains objects a and b. This relationship is called containership or nesting Friendly functions Non member function can not access private data of a class. If two classes A and B want to share a particular function say C to operate on the objects of both these classes, then C++ allows the common function made friendly to both the classes, there by allowing the function to have access to the private data of these classes. Such a function need not be a member of any of these classes. Declare such function as a friend of the classes such as friend void C (void) defined elsewhere in the program like a normal C++ function. function definition does not use either the keyboard friend and the scope operator :: class abc ; forward declaration. It is defined later class xyz { int x ; public : void set_value (int i) { x = i friend void max (xyz, abc) ; ; class abc { int a ; It is defined later public : void set_value (int i) { a = i friend void max (xyz, abc) ; ; // Definition of friend function max outside the classes void max (xyz p, abc q) { if (p.x >= q. a) cout << p.x ; else cout<< q.a main ( ) { abc m; m. set_value (10); xyz n; n. set_value (20); max ( m, n ); No need to use scope operator :: Characteristics of friend function It is not in the scope of the class to which it has been declared as friend. So it can not be called using the object of that class. It can be invoked like a normal function without the help of any object. It can not access the members directly and has to use an object_name and dot membership operator with each member name. It can be declared either in public or private part of a class without affecting its meaning. 12

13 Usually arguments of such functions are objects. A member function of any class can be friend of other class class A { int fun ( );. class B { friend int A :: fun ( ) ; We can also declare all member functions of a one class as the friend functions of another class. In such cases a class is called friend class. class A { friend class B ; Friend functions are often used in operator overloading. Operator Overloading Exciting feature which enhances the power of C++. Operators for built in data type can be overloaded to do the operations on variables of userdefined types. Redefine operator + to concate character strings. string s1 [10] = abc ; string s2 [ 10 ] = def ; string s3 [ 20 ] ; s3 = s1 + s2 ; The semantics of operator can be extended but we can not change its syntax. The general form of the definition if defined outside the class body: return_type class_name :: operator op (list ) {... return_type: type of value returned by the specified operation operator : keyword to be specified before an operator op : operator being overloaded. Operator op becomes a function name. Operator functions must be either member functions or friend functions. class complex { double real, imag ; public: constructor1 complex ( ) { ; constructor2 complex(double x, double y ) { real = x, imag = y declaration complex operator+ (complex c); //end of class complex definition of complex complex :: operator + ( complex c ) operator + { complex temp; return type temp. real = real + c. real ; temp. imag = imag + c. imag return temp ; class name void main ( ) { complex p, q, sum ; p = complex ( 2.0, 3.5 ) ; q = complex ( 2.5, 3.5 ); sum = p + q ; Rules for Overloading Operators Only existing operators can be overloaded. Overloaded operator must have at least one operand that is user-defined type. Some operators can not be overloaded. (e.g.,..* ::? sizeof ) We cannot change the basic meaning of an operator. ( e.g., + can t be used for subtraction) Binary arithmetic operators must explicitly return a value. Binary operators when overloaded through a member functions then left hand operand be an object of the relevant class.

It is possible to have more than one definition for any operator. String operator+ ( string ) ; Vector operator+ ( vector ) ; Matrix operator + ( matrix ) ; Polymorphism Simply means one name - multiple forms. Important feature of OOP. Concept is implemented using overloaded functions of operators to some extent. It is of two types : Compile time Run time Function Overloading Operator overloading Virtual functions 14 Compile time polymorphism o Compiler selects appropriate function/operator at compilation time. o Known as early binding / static binding / static linking. Here object is bound to its function call at compile time. class A { int x; public: void show ( ) { ; class B : public A { int y; public: void show ( ) {. ; How to use member function show ( ) to print the values of both classes A and B? o Since show ( ) is the same in both the places, the function is not overloaded and therefore, static binding does not apply. o Compiler in such cases defers the decision. o It would be nice if the appropriate member function could be selected while the program is running. Run time polymorphism. o C ++ supports a mechanism known as virtual function to achieve run time polymorphism. o At run time, when it is known what class objects are under consideration, the appropriate version of the function is called. o This process is called late binding /dynamic binding. It is a powerful feature of C++. o This requires the use of pointers to objects. Object pointers of virtual functions are used to implement dynamic binding? Pointers to objects o Pointer can point to an object created by a class and are useful in creating objects at run time such as item *ptr ; o Here item is a class with two public functions, say, void get_data ( int a, float b) and void show ( void ). o Object pointer can access the public members ( data / function ) of an object. Assume the following declarations: item x ; item *ptr = &x; o Possible ways of accessing members of an object x. ptr get_data ( 100, 20.5 ) ; ptr show ( ) ; x. get_data ( 100, 20.5 ); x.show ( ) ; (*ptr). get_data ( 100, 20.5 ) ; (*ptr). show ( ) ;

15 o Objects using pointers are created using new operator as item *ptr = new item; o It allocates enough memory for the data members in the object structure and assigns the address of that space to pointer. o The pointer ptr can be used to refer to the members as ptr show ( ). o If a class has a constructor with arguments and does not include an empty constructor, then we should supply arguments when objects are created: item *ptr = new item(10,20). o We can also create an array of objects using pointer item *ptr = new item [10] ; o Here if the class contains constructors, it must also contain an empty constructor. Pointers to Derived classes o pointer defined for base object can also be used for objects of derived class. (because of type compatibility ). Base-class * ptr, b; Derived_class d ; ptr = &b ; ptr = &d valid Using ptr, we can only access those members which are inherited from Base_class.. If a member of Derived_class has the same name as in Base_class, then ptr will always access the base_class member. Virtual Functions Virtual functions are created for implementing late binding. Same function name can be used in both base and derived classes. We have already seen that pointer to base class always executes the functions (same name in base and derived class ) of the base class even if it is redefined in derived class. If function in base class is declared as virtual, then call to derived function is possible. class Base { public: void display ( ) { cout << Display Base ; virtual void show ( ) {. : ; class Derived : public Base { public: void display ( ) { cout << Display Derived ; void show ( ) { ; : ; main ( ) { Base B ; Derived D; Base * bptr ; bptr = &B ; bptr display ( ); bptr show ( ); // These are calls to base functions ( static binding) bptr = &D ; bptr display ( ); bptr show ( ) ; // These are calls to derived functions (dynamic binding) When a function is made virtual, C++ determines which function to use at run time based on the type of object pointed to by the base pointer. Thus by making the base pointer to point to different objects of derived classes, we can execute different versions of the virtual function. Note that we must access virtual functions through the use of a pointer declared to the base class.

Rules for virtual functions The virtual functions must be members of some class. They can not be static members. They are accessed by using object pointers. A virtual function can be a friend of another class. We cannot have virtual constructors but can have virtual destructors. When a base pointer points to derived class, incrementing or decrementing pointer (i.e., pointing to next or previous object) will not be allowed. this pointer C++ uses a unique keyword called this to represent an object that invokes a member function. this is a pointer that points to the object for which this function was called. Call to function max, A. max ( ) sets this pointer to the address of an object A. The starting address is the same as the address of the first variable in the class structure. The pointer this acts as an implicit argument to all the member functions. class ABC { int a ;. Use of private variable a inside a member function like a = 123 is same as this a = 123 ; We have not used this explicitly so far. Important application of this pointer is to return the object it points to. class person { char name [20] ; float age ; public: person( ) {; constructor person ( char * s, float a ){ strcpy ( name, s ) ; age = a ; person &greater ( person &x ) {if ( x. age) > = age ) return x; else return this void display ( void ) { cout << name << age << main ( ) { person p1 ( dam, 20.5 ), p2 ( shyam, 29.0 ), p ; p = p1. greater ( p2 ) ; p. display ( ); //displays elder person Constructors and Destructors Member function for initializing private variables of a class can be included in public part of the class. { int x; int y; public : void getdata (int a, int b) { x = a; y = b Objects of are created by declaration item p, q; Explicit call is made to member function getdata for each object to initialize the private variables of p and q. 16

17 These functions can t be used to initialize the member variables at the time of creation of their objects automatically. If the class (user defined data type) should behave similar to built-in-type, we should be able to initialize objects (class type variable) when they are declared and should be destroyed when go out of scope. C++ provides this facility. Constructor Enables an object to initialize itself when it is created (automatic). Destructor Destroys the object when they are no longer required. Constructor: has the same name as of class { int x; int y; public: item (void) constructor { x = 0; y = 0; Elements of item type are declared as: item p, q, r. Here p, q and r are initialized to 0. Constructor that accepts no parameters is called default constructor Special characteristics of constructor functions: Should be declared in public part. Are invoked automatically when objects are created. Do not have return type, not even void. Can not be inherited though derived class can call the base constructor. Like other C++ functions, they can have default arguments. Can not be referenced through their address. These function use implicit call to operators new and delete when memory allocation is required. Parameterized constructors Now declaration item p will not work { int x; int y; public : item(int a, int b ) parameterized constructor { x = a; y = b Two ways of object declaration using constructors: item p = item ( 2, 3 ) ; explicit call item p ( 2,3 ); implicit call Parameters of constructor can be of any type except that of the class to which it belongs. item (item p) is not valid. Can accept a reference to its own (item& p) (it is called copy constructor) Multiple constructors in a class { int x, y; public:

Overloading of item ( ) {x = 0; y = 0 ; Constructors item ( int a, int b) { x = a; y = b ; item (item & p) { x = p. x ; y = p. y ; Possible declarations item t1; item t2 ( 20, 40 ) ; item t3 ( t2 ); 18 Implicit constructor (provided by compiler C++) Creates objects even though constructor is not defined in the class. In case if we define a constructor, we must also define do-nothing constructor such as item ( ) { ; Constructors with default Argument values Constructor definition item ( int a, int b = 2) { x = a; y = b; Object declaration item t (3) ; Here t. x = 3; t. y = 2; default value item t1 (4,3); then t1. x = 4; t1. y = 3; The missing arguments must be the trailing ones Dynamic constructors Constructors can be used to allocate memory while creating objects. It is called dynamic construction of objects at run time. This is called dynamic construction of objects and is done with the help of new operator class matrix { int * p // pointer to matrix int d1, d2 public : matrix ( int n, int m ); : matrix :: matrix (int n, int m ) { d1 = n ; d2 = m ; p = new int * [d1] ; // array pointer for ( int i= 0 ; i < d1 ; i ++) {p[i] = new int [d2] // creates space for each row ; main ( ) { int m, n ; cin >> m >> n ; matrix A (m, n); // matrix object A is constructed with the help of constructor Here the constructor first creates a vector pointer to an int of size d1 and then space for d2 size to each element. Destructors It is a member function whose name is the same as the class name but is preceded by tilde symbol ~ i.e., ~ item ( ) { ; It never takes any arguments nor it returns any value It is implicitly invoked by compiler upon exiting from the program (block, function ) to clean up storage and it is good practice to declare { int x, y; public: item ( ) {;

19 item ( int a, int b ) { x = a = ; y = b ; ~ item ( ) { ; destructor main ( ) { item t1, t2 (3, 4); : { item t3, t4, t5 (2, 3); : { item t6 (1, 4) ; : : t6 is not available : t3, t4, t5 are not available t1, t2 are not available Constructors in derived classes If base class has constructor without arguments then derived class need not have a constructor function. If any base class contains constructor with one or more arguments, then it is mandatory for the derived class to have a constructor and pass the arguments to the base class constructors. The general format Argument declarations of base constructors ` derived constru (AL1, AL2, ALn, ALB): base1 (al_1), base2 (al_2),, Argument declarations for derived class constructors basen (al_n ) {Body of the derived_constru Actual parameters to be passed to base constructors class A { : public: A (int a, int b) { ;... parameterized constructor class C { : public: C (float x) { ;... parameterized constructor class B : public A, public C { int t ; public: B ( int x, int y, float z, int p): A ( x, y), C ( z) { t = p; cout << "B is initialized";;... Declarartion B beta (2, 4. 2.5, 8)

Unformated I/O Operations 20 ios : istream, ostream, iostream (ios is a general purpose I/O stream). istream is an input stream that declares input functions such as get ( ), getline ( ) and read( ). Overloaded extraction operator is >>. ostream is an output stream that declares output functions such as put ( ) and write ( ). Overloaded insertion operator is <<. iostream is an input/output stream. cin and cout are objects defined in <iostream.h> file for input / output of data of various types. cin >> v1 >> v2 >> >> vn ; and cout << v1 << v2 <<. << vm ; put ( ) and get ( ) functions of cout and cin objects respectively, handle single character input / output operations get ( ) char c ; c = cin. get ( ) cin. get ( c ) cin >> c (will not work properly) put ( ) cout. put (c) // displays the value of c cout. put ( 68 ) // displays character D whose ASCII value of 68 get line ( ) reads line ( terminated by new line character \n ) cin. getline ( line, size) line is a variable which stores characters of line. Termination takes place when size 1 or "\n" which ever occurs first. We can read string ( without blanks in it ) by cin >> name ; write ( ) displays an entire line by writing cout. write ( line, size ); Concatenation of two strings can be displayed as follows: cout. write ( string1, m ). write ( string2, n ); OR cout. write ( string1, m ); cout. write ( string2, n ) ; Working with files A program involves two types of data communication: Data transfer between console unit and the program. Data transfer between the program and a disk file. I/O system of C++ handles file operations similar to console input & output operations. C ++ contains a set of classes that define the file handling methods. ifstream ofstream fstream These classes are derived from fstreambase class and from the corresponding classes in <iostream.h> file. These classes (designed to manage the files) are declared in <fstream.h> <iostream.h> file ios istream streambuf ostream iostream <fstream.h> file ifstream filebuf fstream ofstream fstreambase

Details of the <file stream> classes 21 class contents filebuf - sets the file buffers to read and write. fstreambase - provides operations common to the file streams. It is a base for fstream, fstream & ofstream classes. It contains open ( ) & close ( ) funcs. ifstream - provides input operations. Inherits various functions from istream ( get ( ), get line ( ), read ( ), seek ( ).. ), It contains open( ) with default input mode. ofstream - provides output operations. Inherits various functions from ostream ( put, seekp, tellp, write etc.). It contains open ( ) with default output mode. fstream - supports for simultaneous input/output operations. Inherits all functions from istream, ostream classes through iostream. It contains open ( ) with default input mode. Opening and closing files : File opening can be done in two ways: Using the constructor function of the class for opening one file using one stream. Using the member function open ( ) of the class for opening multiple files using one stream. Using constructor : file name is used to initialize the file stream object. Create a file stream object. (ifstream for input stream & ofstream for output stream) to manage the stream using the appropriate class. Initialize the file object with the desired file name. ifstream infile ( data ) ; // input only ofstream outfile ( result ); // output only Here infile is ifstream object and attached to data file for reading and outfile is ofstream object and attached to result file for writing. We can attach the same file for writing and reading in same/ different programs. Program 1: ofstream outfile ( salary ); program 2: ifstream infile( salary ) ; program 3:. ofstream outfile ( salary );. outfile. close ( ) ;. ifstream infile ( salary ) ;. infile. close ( ) File is closed automatically when the stream object expires (program terminates). Outfile. close ( ) disconnects the file from output stream outfile but object outfile still exists and file can be connected again. Opening files using open ( ) : Used for opening multiple files using the same stream object in sequence. ofstream outfile ; outfile. open ( data1 ) ; ; outfile. close ( ) ; outfile. open ( data2 ); ; outfile. close ( )

22 General format: file_ stream_class stream_object ; stream_object. open ( filename ); At times we may require to use two or more files simultaneously ( merging ). ifstream f1, f2 ; ofstream f3; f1. open ( firstfile ) ; f2. open ( secondfile ) ; f3. open ( mergedfile ) ; Detection of End_of_file While ( f1 ) { terminates when f1 ( object of ifstream class ) returns 0 on reaching end_of_file condition. Note that loop may terminate due to other failures as well. Another approach to detect end_of_file condition is : if ( f1. eof ( )! = 0 ) { exit ( 1 ) ; eof ( ) is a member function of ios class. It returns non zero value if the end_of_file condition is encountered and 0 otherwise. File modes general format: stream_object. open ( file name, mode ); mode ios :: in ios : : out ios : : app ios : : ate ios : : nocreate ios : : noreplace meaning opens for reading only (default) opens for writing only (default) append to end_of_files. go to end_of_file on opening. open fails if file does not exist. open fails if file already exists. Append mode allows us to add data to the end of the file only(output). ios :: ate permits us to add or modify the existing data anywhere in the file. Creating a stream using ifstream & ofstream requires no mode.the class fstream does not provide a mode by default and must be specified explicitly. Mode can combine two or more parameters using OR operator ( ) as fout. open ( data, ios : : app / ios : : nocreate ) Sequential Input / output operations put ( ) and get ( ) functions handle single character ( write & read ) to the associated stream. fstream f 1 ; f 1. open ( Text, ios : : in ios : : out ) ; f 1. get (ch ) ; // gets a character from file f 1. put ( ch ); // puts a character to file write ( ) and read ( ) functions handle the data in binary form ( stored in the disk file in the same format in which they are stored in internal memory ) infile. read ( ( char * ) &x, sizeof (x) ) ; outfile.write ( ( char * ) &x, sizeof (x) ) ; These functions take two arguments. o first is the address of the variable x. o second is the length of that variable in bytes. The address of the variable must be cast to type char * (pointer to character type)

Reading and writing a class object 23 write ( ) copies a class object from memory, byte by byte with no conversion. Only data members are written to the file and not the member functions. read ( ) reads a class object from file to the memory. in_ ; fstream f ; f.open ( stock.dat, ios :: in / ios :: out) ;. f.write (( char *)) &item, sizeof (item) ) ; f. seekg (0) ; // reset to the start f. read ( ( char * ) &item, sizeof ( item) );.. f. close ( ); Functions for manipulating seekg ( ) moves input pointer to a specified location. seekp ( ) moves output pointer to a specified location tellg ( ) gives the current position of input pointer. tellp ( ) gives the current position of output pointer. Infile. seekg(10) moves pointer to the byte number 10 In the statement p = fileout. tellp( ), p is assigned the number of bytes in the file. seekg(offset, refposition): offset is number of bytes a file pointer has to move from the location specified by the parameter refposition which takes one of the following three constants defined in ios class. ios :: beg ios :: cur ios :: end start of the file current position of the pointer end of the file Random Access ( Updation ) If file contains a collection of items/objects of equal length, then to move to a particular (mth ) object, following is done. int ob_length = sizeof ( object ) ; int loc = m * ob_length ; seekg ( loc ); or seekp ( loc ) ; o loc is the start address of mth object. o Total number of objects in a file can be found using ob_length as follows : int n = file_size / ob_length ; o file_size can be obtained using tellg ( ) / tellp ( ) when the file pointer is located at the end of the file.