Unit 5 Muruga
Unit 5 Muruga
Unit 5 Muruga
Prepared by:
Mr.J.Muruganandham, Assistant Professor/ EEE
Unit V
Inheritance: Extending classes, Pointers, Virtual functions and polymorphism, File Handling,
Templates – Exception Handling .
2- MARKS
1. Define inheritance ?
Inheritance is the process of creating new classes from the existing classes. The new classes
are called derived classes. The existing classes are called base classes. The derived classes
inherit all the properties of the base class plus its own properties. The properties of inheritance
do not affect the base classes.
2. What are the types of inheritance?
Single inheritance
Multiple inheritance
Hierarchial inheritance
Multilevel inheritance.
Hybrid inheritance
3. What are the advantages of using a derived class ?
New classes can be derived by the user from the existing classes without any
modification.
It saves time and money.
It reduces program coding time.
It increases the reliability of the program.
4. Define single inheritance.
If a derived class is derived from a base class then it is called single inheritance.
A B
Page 1
EE T46 Data Structures and Object Oriented Programming
If a derived class is derived from more than one base class, then it is called multiple inheritance.
Class A Class B
Class C
B C D
C
9. Define hybrid inheritance.
The combination of one or more types of inheritance is called hybrid inheritance.
A
B C
D
Page 2
EE T46 Data Structures and Object Oriented Programming
Page 3
EE T46 Data Structures and Object Oriented Programming
Page 4
EE T46 Data Structures and Object Oriented Programming
11 Marks
Member Access
How Members of the Base Class Appear in the Derived Class
Specifier
Private members of the base class are inaccessible to the derived class.
Public members of the base class become private members of the derived
class.
Private members of the base class are inaccessible to the derived class.
Private members of the base class are inaccessible to the derived class.
Public members of the base class become public members of the derived
class.
Page 5
EE T46 Data Structures and Object Oriented Programming
B
Syntax
class base class-name
{
//data members
//member functions
};
class derived-class-name: visibility-mode base-class-name
{
//data members
//member functions
};
Example
#include<iostream.h>
#include<conio.h>
#include<string.h>
class student //Class Declaration
{
protected:
int regno,m1,m2,m3,m4,m5; //Data Member
Declaration
char name[20],dept[5];
public:
void getdata( ) //Function to get student details
{
cout<<"\nEnter the register number:";
cin>>regno;
cout<<"\nEnter the name:";
cin>>name;
cout<<"\nEnter the department:";
cin>>dept;
cout<<"\nEnter the mark 1:";
cin>>m1;
cout<<"\nEnter the mark 2:";
cin>>m2;
Page 6
EE T46 Data Structures and Object Oriented Programming
class exam: public student //Deriving new class from base class
{
private:
int total; //Data Member Declaration
char result[6];
float average;
public:
Page 7
EE T46 Data Structures and Object Oriented Programming
ex.display( );
}
Output: STUDENT DETAILS
Enter the register number 12345 Register Number:12345
Enter the name: xyz Name:xyz
Enter the department:ECE Department:ECE
Enter the mark 1: 50 Mark 1:50
Enter the mark 2:60 Mark 2:60
Enter the mark 3:70 Mark 3:70
Enter the mark 4:80 Mark 4:80
Enter the mark 5:50 Mark 5:50
Total:300
Average:60
Result:pass
Multiple inheritance
If a class is derived form morethan one base class, ut us know as multiple inheritance
Class A Class B
Class C
Syntax
class Derived-class-name : Base-class-name1, Base class-name2,…
{
Body of derived class
}
Example
class A
{
……………..
};
class B
{
……………..
};
class C : public A, public B
{
……………
};
Program
// Multiple Inheritance
#include<iostream.h>
#include<conio.h>
#include<string.h>
class student
{
protected:
Page 8
EE T46 Data Structures and Object Oriented Programming
class marks
{
protected:
int m1,m2,m3,m4,m5; //Data Member Declaration
public:
void getmarks() //Function to get student marks
{
cout<<"\nEnter the mark 1:";
cin>>m1;
cout<<"\nEnter the mark 2:";
cin>>m2;
cout<<"\nEnter the mark 3:";
cin>>m3;
cout<<"\nEnter the mark 4:";
cin>>m4;
cout<<"\nEnter the mark 5:";
cin>>m5;
}
};
//Deriving new class from more two base classes
class result: public student,public marks
{
private:
int total; //Data Member Declaration
float average;
char result[6];
public:
void calculation() //Function to calculate result of the student
{
total=m1+m2+m3+m4+m5;
average=float(total)/5;
if(m1>49 && m2>49 && m3>49 && m4>49 && m5>49)
{
strcpy(result,"Pass");
}
else
{
strcpy(result,"Fail");
Page 9
EE T46 Data Structures and Object Oriented Programming
}
}
void display() //Function to display student details
{
cout<<"\n\t\t\tSTUDENT DETAILS";
cout<<"\nRegister Number:"<<regno;
cout<<"\nName:"<<name;
cout<<"\nDepartment:"<<dept;
cout<<"\nMark 1:"<<m1;
cout<<"\nMark 2:"<<m2;
cout<<"\nMark 3:"<<m3;
cout<<"\nMark 4:"<<m4;
cout<<"\nMark 5:"<<m5;
cout<<"\nTotal:"<<total;
cout<<"\nAverage:"<<average;
cout<<"\nResult:"<<result;
}
};
int main()
{
clrscr();
result r; //Object declaration for derived class
getch();
return 0;
}
Output: STUDENT DETAILS
Enter the register number 12345 Register Number:12345
Enter the name: xyz Name:xyz
Enter the department:ECE Department:ECE
Enter the mark 1: 50 Mark 1:50
Enter the mark 2:60 Mark 2:60
Enter the mark 3:70 Mark 4:80
Enter the mark 4:80 Mark 5:50
Enter the mark 5:50 Total:300
Average:60
Result:pass
Page 10
EE T46 Data Structures and Object Oriented Programming
Multilevel inheritance
The mechanism of deriving a class from another derived class is known as multilevel
inheritance. A
C
Syntax:
class Base-class-name
{
Body of Base class
};
class Derived-class-name1:Base-class-name
{
Body of derived class1;
};
class Derived –class-name2:Derived-class-name1
{
Body of derived class2;
};
Program
//Multilevel Inheritance: A -> B -> C
#include<iostream.h>
#include<conio.h>
#include<string.h>
class student //Class Declaration
{
protected:
int regno; //Data Member Declaration
char name[20],dept[5];
public:
void getdata() //Function to get student details
{
cout<<"\nEnter the register number:";
cin>>regno;
cout<<"\nEnter the name:";
cin>>name;
cout<<"\nEnter the department:";
cin>>dept;
}
};
Page 11
EE T46 Data Structures and Object Oriented Programming
class marks: public student //Deriving new class from base class
{
protected:
int m1,m2,m3,m4,m5; //Data Member Declaration
public:
void getmarks() //Function to get student marks
{
cout<<"\nEnter the mark 1:";
cin>>m1;
cout<<"\nEnter the mark 2:";
cin>>m2;
cout<<"\nEnter the mark 3:";
cin>>m3;
cout<<"\nEnter the mark 4:";
cin>>m4;
cout<<"\nEnter the mark 5:";
cin>>m5;
}
};
class result: public marks //Deriving new class from another derived class
{
private:
int total; //Data Member Declaration
float average;
char result[6];
public:
void calculation() //Function to calculate result of the student
{
total=m1+m2+m3+m4+m5;
average=float(total)/5;
if(m1>49 && m2>49 && m3>49 && m4>49 && m5>49)
{
strcpy(result,"Pass");
}
else
{
strcpy(result,"Fail");
}
}
void display() //Function to display student details
{
cout<<"\n\t\t\tSTUDENT DETAILS";
cout<<"\nRegister Number:"<<regno;
cout<<"\nName:"<<name;
cout<<"\nDepartment:"<<dept;
cout<<"\nMark 1:"<<m1;
cout<<"\nMark 2:"<<m2;
cout<<"\nMark 3:"<<m3;
cout<<"\nMark 4:"<<m4;
cout<<"\nMark 5:"<<m5;
cout<<"\nTotal:"<<total;
Page 12
EE T46 Data Structures and Object Oriented Programming
cout<<"\nAverage:"<<average;
cout<<"\nResult:"<<result;
}
};
int main()
{
result r; //Object declaration for derived class
cout<<"\n\t\t\t STUDENT INFORMATION";
r.getdata(); //Calling Base class function using derived object
r.getmarks(); //Calling Base class function using derived object
r.calculation();
r.display();
}
Output: STUDENT DETAILS
Enter the register number 12345 Register Number:12345
Enter the name: xyz Name:xyz
Enter the department:ECE Department:ECE
Enter the mark 1: 50 Mark 1:50
Enter the mark 2:60 Mark 2:60
Enter the mark 3:70 Mark 3:70
Enter the mark 4:80 Mark 4:80
Enter the mark 5:50 Mark 5:50
Total:300
Average:60
Result:pass
Hierarchical inheritance
If anumber of classes are derived from a single base class, it is called ash hierarchial
inheritance
A
B C D
Syntax
class Base-class-name
{
-----------
};
class Derived-class-name1:Base-class-name
{
-----------
};
class Derived-class-nameN:Base-class-name
{
………..
};
Page 13
EE T46 Data Structures and Object Oriented Programming
Programm:
#include <iostream>
#include <conio.h>
using namespace std;
class person
{
char name[100],gender[10];
int age;
public:
void getdata()
{
cout<<"Name: ";
fflush(stdin); /*clears input stream*/
gets(name);
cout<<"Age: ";
cin>>age;
cout<<"Gender: ";
cin>>gender;
}
void display()
{
cout<<"Name: "<<name<<endl;
cout<<"Age: "<<age<<endl;
cout<<"Gender: "<<gender<<endl;
}
};
Page 14
EE T46 Data Structures and Object Oriented Programming
public:
void getdata()
{
person::getdata();
cout<<"Name of Company: ";
fflush(stdin);
gets(company);
cout<<"Salary: Rs.";
cin>>salary;
}
void display()
{
person::display();
cout<<"Name of Company: "<<company<<endl;
cout<<"Salary: Rs."<<salary<<endl;
}
};
int main()
{
student s;
employee e;
cout<<"Student"<<endl;
cout<<"Enter data"<<endl;
s.getdata();
cout<<endl<<"Displaying data"<<endl;
s.display();
cout<<endl<<"Employee"<<endl;
cout<<"Enter data"<<endl;
e.getdata();
cout<<endl<<"Displaying data"<<endl;
e.display();
getch();
return 0;
}
Output Employee
Student Enter data
Enter data Name: Mary White
Name: John Wright Age: 24
Age: 21 Gender: Female
Gender: Male Name of Company: Xyz Consultant
Name of College/School: Abc Academy Salary: $29000
Level: Bachelor
Displaying data
Displaying data Name: Mary White
Name: John Wright Age: 24
Age: 21 Gender: Female
Gender: Male Name of Company: Xyz Consultant
Name of College/School: Abc Academy Salary: $29000
Level: Bachelor
Page 15
EE T46 Data Structures and Object Oriented Programming
Hybrid inheritance
The process of applyin two or more types of inheritance to design a program is called
hybrid inheritance.
Base 1
Derived 1 Derived 2
Derived12
Syntax:
class Base-class-name1
{
………….
};
class Derived-class-name1:Base-class-name1
{
…………
};
class Base-class-name2:Base-class-name 1
{
…………
};
class Derived-class-name12:Derived-class-name1,Base-class-name2
{
………….
}
Programm:
#include <iostream>
using namespace std;
class dimension
{
protected:
int l,b;
public:
void get_dimension()
{
cout<<"Enter Length: ";
cin>>l;
cout<<"Enter breath: :";
}
};
class Rectangle:public dimension
Page 16
EE T46 Data Structures and Object Oriented Programming
{
protected:
float area;
public:
void rec_area()
{
get_dimendion();
area=l*b;
cout<<"Area of Rectangle:"<<area;
}
};
int main()
{
process p;
p.area();
}
Write a C++ program which illustrate that the keyword ‘virtual’ can be used for functions
as well as classes (Nov 2015) (May 2015, May 2016)
Polymorphism
“Polymorphism is the property of the same object to behave differently in different contexts
given the same message”
Page 17
EE T46 Data Structures and Object Oriented Programming
Polymorphis
m
Runtime
Compile Time
VIRTUAL FUNCTIONS
Definition:
A member function whose definition can be changed during run time is called virtual
function. The class which contains virtual function is called polymorphic class and it should be a
base class. Different versions for the virtual function should be present in different derived
classes with same name as virtual function name.
Rules for virtual function:
Functions name must be proceeded by virtual keyword in the base class.
Virtual constructors are not possible. Constructing a derived class object needs specific
construction of the base class sub object within.
The function in the derived class must have same name as of the virtual function defined
in the base class and the same prototype.
The function in the derived class need not be preceded by the virtual keyword.
The virtual function must be defined in the base class, it may have an empty body.
The virtual functions are members of the classes of the hierarchy.
Page 18
EE T46 Data Structures and Object Oriented Programming
Program
//Virtual Function
#include<iostream.h>
#include<conio.h>
class base // Base Class
{
public:
void show() //NON Virtual function
{
cout<<"base - Show \n";
}
virtual void display() //Virtual function
{
cout<<"base - display \n";
}
};
class derived: public base //Deriving new class from base class
{
public:
void show()
{
cout<<"derived - Show \n";
}
void display()
{
cout<<"derived - display \n";
}
};
int main()
{
base *ptr;
base b;
derived d;
cout<<"base object\n";
ptr=&b;
ptr->show();
ptr->display();
cout<<"Base pointer stores derived object address\n";
ptr=&d;
ptr->show();
ptr->display();
getch();
return 0;
}
Output:
base object
base - Show
base – display
base – Show
derived - display
Page 19
EE T46 Data Structures and Object Oriented Programming
Static binding is method resolution dynamic binding refers to method resolution at run
at compile time time
cin>>name;
}
void main( )
{
base * ptr;
dev obj;
clrscr( );
ptr = &obj;
ptr -> getdata( );
ptr -> display( );
getch( );
}
OUTPUT
3. Explain in details about the various Templates and it implementation (May 2016)
A template is a concept which enables us to define generic classes fand functions and
provides support for generic programming. It is used to create a family of class and function
Types of Templates:
Function Template
Class Template
Function Templates:
Function templates are special functions that can operate with generic type. Function
templates are those functions which can handle different data types without separate code for
each of them.
Syntax:
Template<Class T>
Return_type function_name(Arguments of type T)
{
//Body of function
}
Page 21
EE T46 Data Structures and Object Oriented Programming
Example:
#include <iostream>
#include <string>
using namespace std;
template <class T>
T Maximum (T a, T b)
{
if(a>b)
Return a;
else
Return b;
}
int main ( )
{
int i = 39;
int j = 20;
cout << "Maximum(i, j): " << Maxmum(i, j) << endl;
double f1 = 13.5;
double f2 = 20.7;
cout << "Maximim(f1, f2): " << Maximum(f1, f2) << endl;
char s1 = "Hello";
char s2 = "World";
cout << "Maximum(s1, s2): " << Maximum(s1, s2) << endl;
return 0;
}
Page 22
EE T46 Data Structures and Object Oriented Programming
int main ( )
{
int i = 39;
float j = 20.65;
Maximum(i, j):
int f1 = 13.5;
char f2 = ‘x’;
Maximim(f1, f2);
Float s1=20.6
char s2 = ‘z’
Maximum(s1, s2;
return 0;
}
Example:
#include<iostream> Cout<<”Normal Fcn”;
Using namespace std; Cout<<”The value of x”;<<x;
Template<class T> }
Void show(T x) Int main( )
{ {
Cout<<”Template Fcn”; Show(10);
Cout<<”The value of x”;<<x; Show(10.5);
} Show(‘a’);
Void show(int x) Returen 0;
{ }
Class Template
Syntax:
Template <class a_type>
Class class_name
{
//class member specification
//with anonymous type T
// Wherever appropriate
}
Example:
#include <iostream>
using namespace std;
template<class T>
Page 23
EE T46 Data Structures and Object Oriented Programming
class math
{
T a;
public:
math(T x, T y)
{
a=x;
b=y;
}
void get_max()
{
if(a>b)
{
cout<<a<<" Max";
}
else
{
cout<<b<< " Max";
}
}
};
int main()
{
math<int>ob(10,20);
ob.get_max();
math<float>ob1(19.5,0200.36);
ob1.get_max();
math<Char>ob2(‘a’,’b’);
ob2.get_max();
return 0;
}
Class template with multiple paramenter:
If more then one generic data type in ca class template, it should be declared as a
comma-separated list within the template specification.
Syntax:
Template<Class T1, Class T2>
Class classname
{
//Body of the class
}
Example:
#include <iostream>
using namespace std;
template<class T1, class T2>
class math
{
T1 a;
T2 b;
public:
Page 24
EE T46 Data Structures and Object Oriented Programming
math(T1 x, T2 y)
{
a=x;
b=y;
}
void get_max()
{
if(a>b)
{
cout<<a<<" Max";
}
else
{
cout<<b<< " Max";
}
}
};
int main()
{
math<char, int>ob('a',0);
math<float, int>ob1(19.5,0200.36);
ob1.get_max();
return 0;
}
Exception handling is a mechanism that separates code that detects and handles exceptional
circumstances from the rest of your program. Ntoe that an exceptional circumstance is not
necessarily an error.
It perfom the following task:
Find the problem(Hit the exception)
Indorm that an error has occurred(Throw the exception)
Receive the error information(Catch the exception)
Take corrective action(Handle the exception)
Exception handling mechanism is made up of three keywords
1. Try:
The code that throus an exception should be enclosed in a try block(surrounded by
braces)
Page 25
EE T46 Data Structures and Object Oriented Programming
2. Throw:
When a exception is detected, it is thrown using a throw statement in the try block
3. Catch:
The exception that is thron in the try block has to be caught in catch block
Syntax :
Try
{
// Code to be executed
Throw(exception)
}
catch( )
{
//Code to be executed
}
Example program:
#include <iostream>
using namespace std;
int main()
{
float a,b;
cout<<"Enter the value of a&b";
cin>>a>>b;
try
{
if(b!=0)
{
cout<<"Result:"<<a/b;
}
else
{
throw(b);
}
}
catch(float i)
{
cout<<"Exception catches"<<b;
}
return 0;
}
Multipe catch statements:
When program segment has more than one condition to throw an exception, then the
multiple catch statement with single try statement is used
Page 26
EE T46 Data Structures and Object Oriented Programming
Syntax:
Try
{
Throw(type1 arg);
Throw(type2 arg);
Throw(type3 arg)
}
Catch(type1 arg)
{
}
Catch(type2 arg)
{
}
Catch(type3 arg)
{
}
Program:
Void test(int x)
{
try
{ if(x==1)
throw x;
else if(x==0)
throw ‘x’;
else if(x==-1)
throw 1.0;
}
catch(char c)
{ cout<<”caught a character”;
}
catch(int m)
{
Cout<<”caught a integer”;
}
catch(float f)
{ cout<<”caught a float”; }
}
Void main( )
{
Test(1);
Test(0);
Test(-1);
}
Page 27
EE T46 Data Structures and Object Oriented Programming
Rethrowing an Exception
The handler invokes the following throw statement without tany arguments to rethrow
the exception caught with out processing it. Throw; This causes the current exceotion to be
thrown to the next enclosing try/catch sequence and is caught by a catch statement listed aftaer
that enclosing try block.
Example:
#include<iostream>
Using namespace std;
Void fcn(int y)
{
Try
{
Cout<<”In try block fcn()”<<endl;
Throw y;
}
Catch(int)
{
Cout<<”in catch(int)”<<endl
Throw;
}
}
Int main ()
{
Try
{
Cout<<”In try block of main()”<<endl;
Fcn(5);
}
Catch(int)
{
Cout<<”In main() , catch(int)”<<endl;
}
}
Output:
With throw
In try block of main()
In try block of fcn()
In catch (int)
In main(), catch(int)
Without throw
In try block of main()
In try block of fcn()
In catch (int)
Page 28
EE T46 Data Structures and Object Oriented Programming
Page 29
EE T46 Data Structures and Object Oriented Programming
int main ( )
{
char data[80],name[15];
ifstream infile; //Object Declaration For Input File Stream To Read In A File
int main ( )
{ char data[80],name[15];
ofstream outfile; //Object Declaration For Output File Stream To Write In A File
if(strcmp(data,"$")!=0)
{
outfile<<data<<endl;
}
else
{
break;
}
}
outfile.close();
}
The actual data type of the value of all pointers, whether integer, float, character, or
otherwise, is the same, a long hexadecimal number that represents a memory address. The only
difference between pointers of different data types is the data type of the variable or constant that
the pointer points to.
Using Pointers in C++:
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
and (c) finally access the value at the address available in the pointer variable. This is done by
using unary operator * that returns the value of the variable located at the address specified by
its operand. Following example makes use of these operations:
#include <iostream>
using namespace std;
int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
Page 31
EE T46 Data Structures and Object Oriented Programming
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
On most of the operating systems, programs are not permitted to access memory at
address 0 because that memory is reserved by the operating system. However, the memory
address 0 has special significance; it signals that the pointer is not intended to point to an
accessible memory location. But by convention, if a pointer contains the null (zero) value, it is
assumed to point to nothing.
Page 32
EE T46 Data Structures and Object Oriented Programming
Incrementing a Pointer
We prefer using a pointer in our program instead of an array because the variable pointer can
be incremented, unlike the array name which cannot be incremented because it is a constant
pointer. The following program increments the variable pointer to access each succeeding
element of the array:
#include <iostream>
using namespace std;
const int MAX = 3;
int main ()
{
int var[MAX] = {10, 100, 200};
int *ptr;
// let us have array address in pointer.
ptr = var;
for (int i = 0; i < MAX; i++) {
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
// point to the next location
ptr++;
}
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
Page 33
EE T46 Data Structures and Object Oriented Programming
Decrementing a Pointer:
The same considerations apply to decrementing a pointer, which decreases its value by
the number of bytes of its data type as shown below:
#include <iostream>
using namespace std;
const int MAX = 3;
int main ()
{
int var[MAX] = {10, 100, 200};
int *ptr;
// let us have address of the last element in pointer.
ptr = &var[MAX-1];
for (int i = MAX; i > 0; i--) {
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
// point to the previous location
ptr--;
}
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
Address of var[3] = 0xbfdb70f8
Value of var[3] = 200
Address of var[2] = 0xbfdb70f4
Value of var[2] = 100
Address of var[1] = 0xbfdb70f0
Value of var[1] = 10
Pointer Comparisons
Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and
p2 point to variables that are related to each other, such as elements of the same array, then p1
and p2 can be meaningfully compared. The following program modifies the previous example
one by incrementing the variable pointer so long as the address to which it points is either less
than or equal to the address of the last element of the array, which is &var[MAX - 1]:
#include <iostream>
using namespace std;
const int MAX = 3;
int main ()
{
int var[MAX] = {10, 100, 200};
int *ptr;
// let us have address of the first element in pointer.
ptr = var;
int i = 0;
while ( ptr <= &var[MAX - 1] )
{
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
Page 34
EE T46 Data Structures and Object Oriented Programming
int *ptr[MAX];
This declares ptr as an array of MAX integer pointers. Thus, each element in ptr, now holds a
pointer to an int value. Following example makes use of three integers which will be stored in
an array of pointers as follows:
#include <iostream>
using namespace std;
const int MAX = 3;
int main ()
{
int var[MAX] = {10, 100, 200};
int *ptr[MAX];
Page 35
EE T46 Data Structures and Object Oriented Programming
You can also use an array of pointers to character to store a list of strings as follows:
#include <iostream>
using namespace std;
const int MAX = 4;
int main ()
{
char *names[MAX] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali",
};
for (int i = 0; i < MAX; i++) {
cout << "Value of names[" << i << "] = ";
cout << names[i] << endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of names[0] = Zara Ali
Value of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali
A variable that is a pointer to a pointer must be declared as such. This is done by placing
an additional asterisk in front of its name. For example, following is the declaration to declare a
pointer to a pointer of type int:
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that
value requires that the asterisk operator be applied twice, as is shown below in the example:
#include <iostream>
using namespace std;
int main () {
int var;
int *ptr;
int **pptr;
var = 3000;
// take the address of var
ptr = &var;
Page 36
EE T46 Data Structures and Object Oriented Programming
#include <iostream>
using namespace std;
// function declaration:
double getAverage(int *arr, int size);
int main ()
{
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
// pass pointer to the array as an argument.
avg = getAverage( balance, 5 ) ;
// output the returned value
cout << "Average value is: " << avg << endl;
return 0;
}
Page 37
EE T46 Data Structures and Object Oriented Programming
Pointer to function:
#include <iostream>
using namespace std;
float average(float x,float y,float z)
{
return (x+y+z)/3;
}
int main()
{
float a=10,b=20,c=50;
float avg;
float (*p)(float,float,float);
p=&average;
avg=(*p)(a,b,c);
cout<<avg;
}
Page 38