UnitII Inheritance and Pointers Prepared By Mr Hule

Unit-II Inheritance and Pointers Prepared By Mr. Hule Kuldeep(ME-CSE)

Unit Objectives Saturday, January 1, 2022 1. Define inheritance relationships between classes, including public, protected, and private inheritance. 2. Learn how to write class definitions and member function definitions for several classes in an inheritance relationship 3. Discuss pointer types and pointer variables. 4. Discuss how to create a permanent or temporary binding between a pointer variable and a data variable. 5. Discuss how to retrieve and change data in a data variable through the pointer variable. 6. Discuss relations between arrays and pointers, and discuss array arithmetic. 7. Discuss relations between arrays and functions, 8. Discuss about how the Firefox & Thunderbird software was developed with the help of C++. 2

Unit Contents Saturday, January 1, 2022 1. Inheritance: ü Inheritance- Base Class and derived Class, protected members, relationship between base Class & derived Class. ü Constructor and destructor in Derived Class, Overriding Member Functions, Public and Private Inheritance ü Types of Inheritance, Class Hierarchies, Ambiguity in Multiple Inheritance, Virtual Base Class, Abstract class, Friend Class, Nested Class. 2. Pointer: ü Pointers, declaring and initializing pointers, indirection Operators, Memory Management: new and delete, ü Pointers to Objects, this pointer, Pointers to Pointers, Null pointer, void pointer, Pointers to Derived classes ü Pointers Vs Arrays, accessing Arrays using pointers, Arrays of Pointers ü Function pointers, Passing pointers to functions, Return pointers from functions 3. Case study: Know about Firefox and Thunderbird as popular softwares developed using C++ 3

Session 8: Introduction to Inheritance Concept 4 Content: 1. Introduction to C++ Inheritance 2. Protected Members 3. Inheritance – Terminology and Notation 4. Relationship between Base class & Derived class 5. Constructor & Destructor in Derived class

Introduction to C++ Inheritance § Provides a way to create a new class from an existing class § The new class is a specialized version of the existing class § Consider Example of Insects. § Concept Video Link 5 Saturday, January 1, 2022

6 class B { ……. . //500 Statements ………. }; Son class A { ……. . //1000 Statements ………. }; Father Grand Father Why Inheritance? Saturday, January 1, 2022 class C { ……. . //500 Statements ………. };

Protected Members Saturday, January 1, 2022 § Private member of a base class cannot be inherited. § Protected members of a base class are like private members, except they may be accessed by derived classes. § Protected members are inaccessible to all other code in the program. § The base class access specification determines how private, protected, and public base class members are accessed when they are inherited by the derived class. 7

Saturday, January 1, 2022 Difference Between Private and Protected in C++ Basis for comparison 8 Private Protected Inheriting property to the derived class Derived class cannot access base class private members. Derived class can access base class protected members. Accessibility Private members of the class are inaccessible out of the class scope. Protected members of the class are inaccessible out of the class scope except the class derived immediately. Accessible from own class Yes Accessible from derived class No Yes Accessible from outside No No

Saturday, January 1, 2022 Inheritance and the Is-a Relationship § When one object is a specialized version of another object, there is an is-a relationship between them. § For example, a grasshopper is an insect. Here a few other examples of the is-a relationship. § A poodle is a dog. § A car is a vehicle. § A flower is a plant § A rectangle is a shape. § When an is-a relationship exists between objects, it means that the specialized object has all of the characteristics of the general object, plus additional characteristics that make it special. § In object-oriented programming, inheritance is used to create an is-a relationship between classes. 9

Saturday, January 1, 2022 Inheritance – Terminology and Notation Derived Class Base Class § Base class (or parent) – inherited from § Derived class (or child) – inherits from the base class § Notation: class Bank 90 s { private: long int accountno, …. . public: void add. Money(); void withdraw. Money(); void take. Loan(); void display. Account. Details(); }; class Bank 20 s : public Bank 90 s { private: accountno, …. public: void online. Money. Transfer(); void online. Pay. Cheques(); }; 10 Object of the derived class has: • all members defined in child class • all members declared in parent class object of the derived class can use: • all public members defined in child class • all public members defined in parent class

Saturday, January 1, 2022 Relationship between Base class & Derived class § Inheritance is important feature in OOP which allows reusability of the code. § Fundamental idea behind the inheritance is that-make use of data members & member functions of base class in derived class along with some additional functionality present in derived class. § Secondly if there are multiple derived classes, & if there is a need for some modifications in the code, then those modifications need to be carried out in all derived classes. § If we use inheritance then repetition of code can be avoided. § Example. 11

Saturday, January 1, 2022 Base Class Vs Derived Class 12

Saturday, January 1, 2022 Class Access Specifiers § public – object of derived class can be treated as object of base class (not vice-versa) § protected – more restrictive than public, but allows derived classes to know details of parents § private – prevents objects of derived class from being treated as objects of base class. 13

Saturday, January 1, 2022 Inheritance vs. Access How inherited base class members appear in derived class Base class members 14 private: x protected: y public: z private base class x is inaccessible private: y private: z private: x protected: y public: z protected base class x is inaccessible protected: y protected: z private: x protected: y public: z public base class x is inaccessible protected: y public: z Concept Video Link

Saturday, January 1, 2022 More Inheritance vs. Access class Grade private members: char letter; float score; void calc. Grade(); public members: void set. Score(float); float get. Score(); char get. Letter(); When Test class inherits from Grade class using public class access, it looks like this: 15 class Test : public Grade private members: int num. Questions; float points. Each; int num. Missed; public members: Test(int, int); private members: int num. Questions: float points. Each; int num. Missed; public members: Test(int, int); void set. Score(float); float get. Score(); float get. Letter();

Saturday, January 1, 2022 More Inheritance vs. Access class Grade private members: char letter; float score; void calc. Grade(); public members: void set. Score(float); float get. Score(); char get. Letter(); When Test class inherits from Grade class using protected class access, it looks like this: 16 class Test : protected Grade private members: int num. Questions; float points. Each; int num. Missed; public members: Test(int, int); private members: int num. Questions: float points. Each; int num. Missed; public members: Test(int, int); protected members: void set. Score(float); float get. Score(); float get. Letter();

Saturday, January 1, 2022 More Inheritance vs. Access class Grade private members: char letter; float score; void calc. Grade(); public members: void set. Score(float); float get. Score(); char get. Letter(); When Test class inherits from Grade class using private class access, it looks like this: 17 class Test : private Grade private members: int num. Questions; float points. Each; int num. Missed; public members: Test(int, int); private members: int num. Questions: float points. Each; int num. Missed; void set. Score(float); float get. Score(); float get. Letter(); public members: Test(int, int);

Saturday, January 1, 2022 Constructors and Destructors in Base and Derived Classes § Derived classes can have their own constructors and destructors § When an object of a derived class is created, the base class’s constructor is executed first, followed by the derived class’s constructor § When an object of a derived class is destroyed, its destructor is called first, then that of the base class § Example. 18

Saturday, January 1, 2022 Passing Arguments to Base Class Constructors § Allows selection between multiple base class constructors § Specify arguments to base constructor on derived constructor heading: § § derived. Class(int x, int y): base. Class(y) Can also be done with inline constructors Must be done if base class has no default constructor It is not necessary that to maintain the sequence. Example. derived class constructor base class constructor derived. Class: : derived. Class(int x, int y): base. Class(y) 19 derived constructor parameter base constructor parameters

Saturday, January 1, 2022 Quiz on Session 8 1. base class and derived class relationship comes under a) b) c) d) Inheritance Polymorphism encapsulation None a) Inheritance 3. Inheritance allow in C++ Program? a) Class Re-usability b) Creating a hierarchy of classes c) Extendibility d) All 20 2. C++ Inheritance relationship is_ a) Association b) Is-A c) Has-A d) None b) Is-A 4. Functions that can be inherited from base class in C++ program a) Constructor b) Destructor c) Static function d) None

Programming Challenges 1. Suppose a program has the following class declarations: class Shape { private: double area; public: void set. Area(double a) { area = a; } double get. Area() { return area; } }; class Circle : public Shape { private: double radius; public: void set. Radius(double r) { radius = r; set. Area(3. 14 * r); } double get. Radius() { return radius; } }; Answer the following questions concerning these classes: a) When an object of the Circle class is created, what are its private members? b) When an object of the Circle class is created, what are its public members? c) What members of the Shape class are not accessible to member functions of the Circle class? 21 2. Saturday, January 1, 2022 Define classes to appropriately represent class hierarchy as shown in Below figure. Use constructors for both classes and display Salary for a particular employee.

Session 9: Types of Inheritance Content: 1. Types of Inheritance 2. Overriding Member Functions 3. Class Hierarchies 4. Ambiguity in Inheritance: 22 1. 2. 3. Ambiguity in Multiple Inheritance: Diamond Problem with Hybrid/Multipath Inheritance Virtual Base Class 5. Friend Class

Inheritance § Inheritance is one of the basic features of object oriented programming. § In the process of inheritance, one object can acquire the properties of another class. Type of class Base Class Definition A class that is inherited is called a base class. In below diagram, the class 'vehicle' is a base class. The class that does the inheriting is called a Derived Class derived class. In below diagram, the class 'car' is a derived class. 23 Saturday, January 1, 2022

Types of Inheritance Single Inheritance Multilevel Inheritance Multiple Inheritance Hierarchical Inheritance Hybrid Inheritance 24 Saturday, January 1, 2022

Single Inheritance Saturday, January 1, 2022 § In this type of inheritance, one Derived class is formed by acquiring the properties of one Base class. Class Name Type A Base class Derived B class Explanation It is base class in the above program Class derives the properties of class A Let us Understand with Example 25

Multilevel Inheritance Saturday, January 1, 2022 § In this type of inheritance, derived class is formed by acquiring the properties of one base class. § Again same derived class is used as a base class and another class is derived from this. Class Name Type Explanation A Base class It is base class in the above program B Base class for C and derived class for A - C Derived class It contains all the properties of class A and B so we can consider this as derived class of A also 26 Example

Multiple Inheritance Saturday, January 1, 2022 § In this type of inheritance, one Derived class is formed by acquiring the properties of multiple Base classes. Class Name A B C 27 Type Base class Derived class Explanation It is base class in the above program Class derives the properties of class A and B Lets understand with Example

Hierarchical Inheritance Saturday, January 1, 2022 § In this type of inheritance, multiple subclass are formed by acquiring the properties of one Base class. Class Name A B C D 28 Type Base class Derived class Explanation It is base class in the above program Class derives the properties of class A Lets understand with Example

Hybrid Inheritance Saturday, January 1, 2022 § In this type of Inheritance, the Derived class is formed by any legal combination of above four forms. 29 Lets understand with Example

Problem Statement Saturday, January 1, 2022 Create Student bio-data using following classes & Multiple inheritance concept of C++. 30

Class Hierarchies § Inheritance is a mechanism in which using base Saturday, January 1, 2022 Undergraduate class, various classes can be derived. § The class hierarchy is normally represented by Student Masters class diagram. § Implementation of class hierarchy is possible using Hierarchical Inheritance. Ph. D Person Teaching Staff Non-Teaching Staff 31

Overriding Member Functions § It is the redefinition of base class function in its derived class with same signature i. e. return type and parameters. § But the task carried out with it is different. It can only be done in derived class. § Let's see a simple example of Function overriding in C++ § How to access the overridden function in the base class from the derived class? § To access the overridden function of the base class from the derived class, scope resolution operator : : is used. For example, § If you want to access get. Data() function of the base class, you can use the following statement in the derived class. Base: : get. Data(); 32

Saturday, January 1, 2022 Ambiguity in Multiple Inheritance 34

Diamond Problem with Hybrid/Multipath Inheritance Saturday, January 1, 2022 § Two ways to avoid C++ ambiguity: 1. Using scope resolution operator 2. Using virtual base class 35

Virtual Base Class § The duplication of inherited members due to multiple paths can be avoided by making the common base class(ancestor class) as virtual base class while declaring the direct or intermediate base classes. 36 class_A { ……. . }; class_B : virtual public class_A { ……. . }; class_C : virtual public class_A { ……. . }; class_D : public class_B, public class_C { ……. . // only one copy of class_A will be inherited ……. . };

Abstract Class Saturday, January 1, 2022 § Sometimes implementation of all function cannot be provided in a base class because we don’t know the implementation. Such a class is called abstract class § A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have implementation, we only declare it. § A pure virtual function is declared by assigning =0 in declaration. class Weapon { public: virtual void features() = 0; }; 37 This pure virtual function And, the class Weapon is an abstract class.

Abstract Class Example #include <iostream> using namespace std; class Shape // Abstract class { protected: float l; public: void get. Data() { cin >> l; } // pure virtual Function virtual float calculate. Area() = 0; }; class Square : public Shape { public: float calculate. Area() { return l*l; } }; 38 class Circle : public Shape { public: Output float calculate. Area() Enter length to calculate the area of a square: 4 { return 3. 14*l*l; } }; Area of square: 16 int main() Enter radius to calculate the area of a circle: 5 { Area of circle: 78. 5 Square s; Circle c; cout << "Enter length to calculate the area of a square: "; s. get. Data(); cout<<"Area of square: " << s. calculate. Area(); cout<<"n. Enter radius to calculate the area of a circle: "; c. get. Data(); cout << "Area of circle: " << c. calculate. Area(); return 0; } Saturday, January 38 1, 2022

Friend Class Saturday, January 1, 2022 § Like friend function, a class can also be a friend of another class. § A friend class can access all the private and protected members of other class. § In order to access the private and protected members of a class into friend class we must pass on object of a class to the member functions of friend class. § For example: class B; class A { friend class B; . . . . // class B is a friend class of class A } class B {. . . . } § All member functions of class B will be friend functions of class A. § Thus, any member function of class B can access the private and protected data of class A. But, member functions of class A cannot access the data of class B. 39

Friend Class Example #include<iostream> using namespace std; class Rectangle { int L, B; public: Rectangle() { L=10; B=20; } friend class Square; }; 40 class Square { int S; public: Square() { S=5; } void Display(Rectangle Rect) { cout<<"nnt. Length : "<<Rect. L; cout<<"nnt. Breadth : "<<Rect. B; cout<<"nnt. Side : "<<S; } }; int main() { Rectangle R; Square S; S. Display(R); //Statement 2 } Output Length : 10 Breadth : 20 Side : 5 Saturday, January 40 1, 2022

Saturday, January 1, 2022 Difference Between Friend Function and Friend Class Basis for comparison Friend Function Friend Class Basic It is a function used with a friend keyword to grant a non-member function access to the private members of a class. It is a class used with a friend keyword to access the private members of another class. Forward declaration Must be used. Not mandatory. Use A friend function can be used in some situation of operator overloading. A friend class can be used when a class is created on the top of another class. 41

Local Classes § A class defined within a function is called Local Class. Syntax: void function() { class_name { // class definition } obj; //function body } 42 void fun() { class myclass { int i; public: void put_i(int n) { i=n; } int get_i() { return i; } } ob; ob. put_i(10); cout << ob. get_i(); } Saturday, January 1, 2022

Nested Classes Syntax: class outer_class { //class definition class inner_class { //class definition }; }; 43 Example: Class. X{…. . }; Class. Y{…. }; Class. Z{ X Ob 1; Y Ob 2; }; Saturday, January 1, 2022 Example: class student { int st_id; public: class dob { public: int dd, mm, yy; }dt; void read() //object of X class { dt. dd=25; //object of Y class dt. mm=2; dt. yy=1988; } };

Saturday, January 1, 2022 Why Class within Class instead Inheritance 1. C++ code using multiple inheritance tends to be a bit difficult to maintain. 2. Inheritance locks in a class’s behavior at link time, while class within class allows you to change the behavior of a class during runtime. 3. When you inherit from a class its internals are visible to you. On the other hand, with composite classes the internals of the class you compose with are hidden. 44

Summary of Inheritance Saturday, January 1, 2022 1. Inheritance is the capability of one class to inherit the properties of another class. 2. Inheritance supports reusability of code and is able to simulate the transitive nature of real life objects. 3. A class from which another class is inheriting its properties is called base class and the class inheriting properties is known as a sub class or derived class. 4. When a class inherits from a single class it is known as single inheritance. 5. When a class inherits from multiple base classes it is known as multiple inheritance. 6. When several classes inherit from the same class it is hierarchical inheritance. 7. When a subclass is the base class of another class it is known as multilevel inheritance. 45

Summary of Inheritance Saturday, January 1, 2022 8. When a class inherits from multiple base classes and all of its base classes are subclasses of the same 9. 10. 11. 12. 13. 14. 46 class it is hybrid inheritance. In the publicly derived class the public and protected members of the base class remains same. The derived class constructor is responsible for invoking (and passing arguments to) the base class constructor. The derived class can directly access only the public and protected members of the base class. To make the private member of a class inheritable declare it under protected section of the base class. When a class inherits from more than one base class this is called multiple inheritance. When a derived class and its base class have common ancestor then ambiguity may arise as the derived class contains multiple copies of common ancestor. This can be resolved either by using scope resolution operator : : or by declaring the common ancestor as virtual.

Saturday, January 1, 2022 Quiz on Session 9 1. Virtual Base class __ a) Allows to inherit more than 1 copy of the base class members b) Strict the path of inheritance c) Is qualified as virtual in base class definition d) None of these c) Is qualified as virtual in base class definition 3. Composition is referred to as _______ a) “is a” relationship b) “extends to” relationship c) Both A & B d) “has a” relationship 47 2. When 2 or more classes are used within another class definition, it is called _____ a) b) c) d) Inheritance Aggregation Both A & B None of these b) Aggregation 4. Pure virtual functions _____ a) Have to be redefined in the inherited class b) Cannot have public access specification c) Are mandatory for a virtual class d) None of these a) Have to be redefined in the inherited class

Programming Challenges 2. 48 Write a program to implement following inheritance as shown in Figure. Accept and display data for one object of class result. 2. Saturday, January 1, 2022 Write C++ program for following multilevel inheritance. Accept and display data for one car with all details.

Session 10: Pointers in C++ Contents: 1. Getting the Address of a Variable 2. Pointers-Indirection operator 1. 2. Initialization of Pointer Variable Accessing variable through Pointer 3. Dynamic Memory Management using new & delete operator 4. Pointers to Objects 49

Saturday, January 1, 2022 Getting the Address of a Variable § CONCEPT: The address operator (&) returns the memory address of a variable. § Every variable is allocated a section of memory large enough to hold a value of the variable’s data type. § On a PC, for instance, it’s common for one byte to be allocated for chars, two bytes for shorts, four bytes for ints, longs, and floats, and eight bytes for doubles. Each byte of memory has a unique address. § A variable’s address is the address of the first byte allocated to that variable. § Suppose the following variables are defined in a program: char letter; short number; float amount; 50

Saturday, January 1, 2022 Getting the Address of a Variable Continued. . § When the address operator (&) is placed in front of a variable name, it returns the address of that variable. § Here is an expression that returns the address of the variable num: &num § And here is a statement that displays the variable’s address on the screen: cout << # § NOTE: Don’t confuse the address operator with & symbol used when defining a reference variable 51 /*This program uses the & operator to determine a variable's address and the sizeof operator to determine its size. */ #include <iostream> using namespace std; int main() { int x = 25; cout << "The address of x is " << &x << endl; cout << "The size of x is " << sizeof(x) << " bytesn"; cout << "The value in x is " << x << endl; return 0; } NOTE: The address of the variable x is displayed in hexadecimal. This is the way addresses are normally shown in C++.

Saturday, January 1, 2022 Get the Value from the Address Using Pointers § CONCEPT: Pointer variables , which are often just called pointers , are designed to hold memory addresses. § § § 52 With pointer variables you can indirectly manipulate data stored in other variables. Like any variable or constant, you must declare a pointer before you can work with it. The general form of a pointer variable declaration is: type *var-name; When * is used with pointers, it's called the dereference operator. It operates on a pointer and gives the value pointed by the address stored in the pointer. Examples of valid Pointer Variables: int *ip; // pointer to an integer double* dp; // pointer to a double float *fp; // pointer to a float char *ch ; // pointer to character

Advantages of Pointer Saturday, January 1, 2022 1. Allows to pass variables, arrays, functions, strings & structures as function arguments. 2. Allows to returns structure variables from functions. 3. Supports dynamic allocations and deallocations of memory. 4. Variables can be swapped without physically moving them. 5. Allows to establish links between data elements or objects for some complex data structures like sack, queue, LL, tree, etc. 53 53

Saturday, January 1, 2022 Operations on Pointers Variables § There are few important operations, which we will do with the pointers very frequently. a) We define a pointer variables b) Assign the address of a variable to a pointer c) Finally access the value at the address available in the pointer variable. 54

Saturday, January 1, 2022 Initialization of Pointer Variable § CONCEPT: Pointers may be initialized with the address of an existing object. Memory address: 1020 … 1024 88 1032 100 … a int a = 100; int *p = &a; cout << a << " " << &a <<endl; cout << p << " " << &p <<endl; § The value of pointer p is the address of variable a with code p=&a. § A pointer is also a variable, so it has its own memory address 55 … 1024 p Result is: 100 1024 1032

Pointer Assignment Saturday, January 1, 2022 § A pointer is variable data type & hence general rule to assign is value to the pointer which is same as that of an variable data type. § Example: Valid Assignments int a, b, *p 1, *p 2; p 1=&a; 56 Invalid Assignments int a; int a_p; a_p=&a; int a, b, *p 1, *p 2; p 1=&x; p 2=p 1; float b; float *b_p; b_p=b; int a, b, *p 1, *p 2; b=*p 1; int a; char *c_p; c_p=&a;

Accessing variable through Pointer (Indirection Operation) § CONCEPT: The real benefit of pointers is that they allow you to indirectly access and modify the variable being pointed to. § This is done with the indirection operator, which is an asterisk (*). § When the indirection operator is placed in front of a pointer variable name, it dereferences the pointer. § When you are working with a dereferenced pointer, you are actually working with the value the pointer is pointing to. 57

Don’t get confused Saturday, January 1, 2022 § Declaring a pointer means only that it is a pointer: int *p; § Don’t be confused with the dereferencing operator, which is also written with an asterisk (*). They are simply two different tasks represented with the same sign int a = 100, b = 88, c = 8; int *p 1 = &a, *p 2, *p 3 = &c; p 2 = &b; // p 2 points to b p 2 = p 1; // p 2 points to a b = *p 3; //assign c to b *p 2 = *p 3; //assign c to a cout << a << b << c; 58 Result is: 888

Saturday, January 1, 2022 A Pointer Example The code Box diagram main void double. It(int x, int * p) { a 16 *p = 2 * x; } int main(int argc, const char * argv[]) { int a = 16; double. It(9, &a); return 0; } a gets 18 59 x p 9 p (8200) 8192 double. It x (8196) 9 a (8192) 16 main

Saturday, January 1, 2022 Debugging of Pointers: Null Pointer § In C++ 11, the nullptr keyword was introduced to represent the address O. § So, assigning nullptr/NULL to a pointer variable makes the variable point to the address O. § When a pointer is set to the address O, it is referred to as a null pointer because it points to “nothing. ” § Here is an example of how you define a pointer variable and initialize it with the value nullptr: int *ptr = nullptr; NOTE: If you are using an older compiler that does not support the C++ 11 standard, you should initialize pointers with the integer 0, or the value NULL. The value NULL is defined in the iostream header file (as well as other header files) to represent the value O. 60

Saturday, January 1, 2022 Example for NULL Pointer // This program stores the address of a variable in a pointer. #include <iostream> using namespace std; int main() { int x = 25; // int variable int *ptr = NULL; // Pointer variable, can point to an int ptr = &x; // Store the address of x in ptr cout << "The value in x is " << x << endl; cout << "The address of x is " << ptr << endl; return 0; } Program Output: The value in x is 25 The address of x is 0 x 7 e 00 61 § To check for a null pointer you can use an if statement as follows: if(ptr) // succeeds if p is not null if(!ptr) // succeeds if p is null

Saturday, January 1, 2022 Dynamic Memory Allocation: new operator § CONCEPT: Variables may be created and destroyed while a program is running. § The program to create our own variables “on the fly” is called dynamic memory allocation and is only possible through the use of pointers. § Dynamically memory allocation is done through new operator at the runtime. § Assume a program has a pointer to an int defined as int *iptr = NULL; § Here is an example of how this pointer may be used with the new operator: iptr = new int; § This statement is requesting that the computer allocate enough memory for a new int variable. § The operand of the new operator is the data type of the variable being created. § Once the statement executes, iptr will contain the address of the newly allocated memory. 62

Saturday, January 1, 2022 Dynamic Memory Allocation: new operator Continued…. § A value may be stored in this new variable by dereferencing the pointer: *iptr = 25; § Any other operation may be performed on the new variable by simply using the dereferenced pointer. § Here are some example statements: // Display the contents of the new variable. cout << *iptr; // Let the user input a value. cin >> *iptr; // Use the new variable in a computation. total += *iptr; 63

Saturday, January 1, 2022 Dynamic Array § A more practical use of the new operator is to dynamically create an array. § Here is an example of how a 100 -element array of integers may be allocated: iptr = new int[100]; § Once the array is created, the pointer may be used with subscript notation to access it. For instance, the following loop could be used to store the value 1 in each element: for (int count = 0; count < 100; count++) iptr[count] = 1; § When memory cannot be dynamically allocated, C++ throws an exception and terminates the program. Throwing an exception means the program signals that an error has occurred. 64

Saturday, January 1, 2022 Dynamic Memory Deallocation: delete operator § When a program is finished using a dynamically allocated chunk of memory, it should release it for future use. § The delete operator is used to free memory that was allocated with new. § Here is an example of how delete is used to free a single variable, pointed to by iptr : delete iptr; § If iptr points to a dynamically allocated array, the [] symbol must be placed between delete and iptr : delete [] iptr; § Failure to release dynamically allocated memory can cause a program to have a memory leak. § WARNING! Only use pointers with delete that were previously used with new. If you use a pointer with delete that does not reference dynamically allocated memory, unexpected problems could result! 65 Let’s Take an Example

Pointers to Objects Saturday, January 1, 2022 § CONCEPT: Pointers and dynamic memory allocation can be used with class objects and structures. § Pointers can be defined to hold the address of an object, which is created statically or dynamically 33, Joseph void read_data( ) void print_data( ) st 2 FCDA 4 66 Statically created object: student *stp; stp = &st; Dynamically created object: student *stp; stp = new student;

Saturday, January 1, 2022 Pointers to Objects – Accessing Members § To access the members of the student object through the pointer st. Because *st is just another way of accessing st, you might think that the expression *st. st_name § will access st. st_name, but this is not so. § To get it right, you must use parentheses to force the indirection operator * to be applied first, as shown here: (*st). st_name § The following statements will correctly set the values of the Student to Kuldeep and 30. (*st). st_name=“Kuldeep”; (*st). st_age=30; 67

Saturday, January 1, 2022 Pointers to Objects – Accessing Members § To solve this problem, C++ provides the structure pointer operator -> is to use when you want to access a member of a class object through a pointer. It consists of a hyphen - and a greater than symbol > written next to each other to look like an arrow. § Using this operator, you can set the name & age of the student with these statements: st->name=“Kuldeep”; st->age=30; § Also you can call class member methods through arrow operator as: st->get. Name(); st->get. Age(); 68

Saturday, January 1, 2022 Accessing Private Members of class using Pointer § We can’t access the private members of the class from outside. We need to make use of the public function. § However, we can return the address of the private member to main & using pointer variable this private member can be accessed. § For example: #include<iostream> using namespace std; class Testing { private: int i; public: void put(){ cout<<"n Enter Some value: "; cin>>i; } int *get() { return &i; } }; 69 int main() { Testing t; t. put(); int *p=t. get(); int a=*p; cout<<"n Value of i: "<<a; *p=100; a=*p; cout<<"n Modified value of i: "<<a; return 0; }

Quiz on Session Saturday, January 1, 2022 1. Write a statement that displays the address of the variable count. Answer: cout<<“Address of the count variable is ”<<&count; 2. Write the definition statement for a variable flt. Ptr. The variable should be a pointer to a float. And point to another float variable. Answer: float a=5. 6 f; float *flt. Ptr=&a; 3. List three uses of the * symbol in C++. Answer: Used as multiplication operator, Used to declare pointer variable, Used as dereference operator, Used with assignment operator. 4. Rewrite the following loop so it uses pointer notation (with the indirection operator) instead of subscript notation. for (int x = 0; x < 100; x++) cout << arr[x] << endl; Answer: for(int x = 0; x < 100; x++) cout << *(arr+x) << endl; 5. What is a null pointer? Answer: A pointer that contains the address 0. 70

Session 11: Pointer & Array Contents: 1. Pointer Arithmetic 2. Accessing Arrays using Pointers 3. Array of Pointer 4. Pointer to String 71

Pointer Arithmetic Saturday, January 1, 2022 § Pointer arithmetic is especially useful with arrays because the elements in an array occupy consecutive memory addresses. § C++ Supports 4 arithmetic operations as: 1. Addition(+) 2. Subtraction(-) 3. Incrementation (++) 4. Decrementation (--) § Pointer are not permitted to perform following arithmetic operations: 1. To multiply or Divide 2. To operates the bitwise shift and mask operations 3. To add or Subtract type float or double to pointers. 72

Saturday, January 1, 2022 Pointer Arithmetic Continued… § Let us consider that ptr is an integer pointer which points to the address 1000. § Assuming 32 -bit integers, let us perform the following arithmetic operation on the pointer: ptr++ § the ptr will point to the location 1004 because each time ptr is incremented, it will point to the next integer. § Note : § ptr + 1 does not return the memory address after ptr, but the memory address of the next object of the type that ptr points to. § Pointers contain addresses. Adding two addresses makes no sense. 73

Pointer Comparisons Saturday, January 1, 2022 § C++’s relational operators may be used to compare pointer values. § Pointers may be compared by using any of C++’s relational operators: > < == != >= <= § NOTE: Comparing two pointers is not the same as comparing the values the two pointers point to. if (ptr 1 < ptr 2) Compares the addresses of the pointed variables respectively. § The following statement, however, compares the values that ptr 1 and ptr 2 point to: if (*ptr 1 < *ptr 2) Compares the values of the pointed variables respectively. 74

Saturday, January 1, 2022 Pointer Arithmetic with Increment & Decrement 75 Operation Description P++ P=P + sizeof(data-type) – Execute before then increment ++P P=P + sizeof(data-type) – Increment before then execute P-- P=P - sizeof(data-type) – Execute before then decrement --P P=P - sizeof(data-type) – Decrement before then execute *(P++) Reprieve contents before then increment *(++P) Increment before then Reprieve contents (*P)++ Increment contents of location pointed by P ++(*P) Increment contents of location pointed by P depending on type of contents. *(P--) Reprieve contents before then Decrement *(--P) Decrement before then Reprieve contents (*P)-- Decrement contents of location pointed by P --(*P) Decrement contents of location pointed by P depending on type of contents.

Saturday, January 1, 2022 Accessing Arrays using Pointers § CONCEPT: Array names can be used as constant pointers, and pointers can be used as array names. § This means that an array name is really a pointer. § Pointers are meant for storing the address of the variable. The pointer can point to any cell of array. § For example: int *ptr; int v[3]; ptr= &a[1]; //address of 1 st element of array a is stored in pointer variable. § It is possible to store the base address of array to pointer variable and entire array can be scanned using this pointer variable. 76 int main() { int v[3], *ptr; int i; ptr=&v[0]; //storing base address of array cout<<"nt Address of an array: "; for(i=0; i<3; i++) cout<<"nt The v["<<i<<"] is: "<<&v[i]; cout<<"nt Address using pointer: n"; for(i=0; i<3; i++) cout<<"nt The ptr#"<<i<<" is: "<<ptr+i; return 0; }

Saturday, January 1, 2022 Accessing Arrays using Pointers § Consider the declaration § § int v[20], *p; And Valid assignment: p=&v[0]; In C++, when you add a value to a pointer, you are actually adding that value times the size of the data type being referenced by the pointer. In other words, if you add one to numbers, you are actually adding 1 * sizeof(datatype) to numbers. Then following are some of the valid equalities for accessing array : § p++==&v[1] § *p==v[0] § *(p+5)==&v[5] 77

Saturday, January 1, 2022 Accessing Arrays using Pointers ü When working with arrays, remember the following rule: array[index] is equivalent to *(array + index ) 78

Problem Statement Saturday, January 1, 2022 1. WAP to demonstrate the use of relational operator to compare the pointer variable. 2. WAP to search a number from an array using pointer to array. 3. WAP to update a number at location of array using pointer to array. 4. WAP to delete a number at location of array using pointer to array. 79

Array of Pointers Saturday, January 1, 2022 § Syntax for array of pointers to an integer: § int *arr[MAX]; § This declares ptr as an array of MAX integer pointers. Thus, each element in ptr, now holds a pointer to an int value. 80 #include <iostream> using namespace std; int main () { int var[3] = {10, 100, 200}; int *ptr[3]; for (int i = 0; i < 3; i++) ptr[i] = &var[i]; // assign the address of integer. for (int i = 0; i < 3; i++) { cout << "Value of var[" << i << "] = "; Output: cout << *ptr[i] << endl; Value of var[0] = 10 } Value of var[1] = 100 return 0; Value of var[2] = 200 } Working of C++ Pointers with Arrays

Saturday, January 1, 2022 Pointer to String § String is nothing but array of characters terminated by special character ‘ ’. § Pointer to string is a pointer to character datatype which points to the base address of string. § Syntax for declaring pointer to string: char *pointer_variable_name; § If string is char str[10] & pointer is: char *ptr; § Then to initialize pointer use either: ptr=str; Or ptr=str[0]; 81

Saturday, January 1, 2022 82 #include<iostream> using namespace std; int main() { char *p, str[15]; int length=0; cout<<"Enter the string: "; cin>>str; p=str; Output: while(*p!='