0% found this document useful (0 votes)
26 views11 pages

VPMP Unit 5

This document covers Unit 5 of Basic Object Oriented Programming, focusing on polymorphism, virtual functions, and file handling in C++. It explains the use of the 'this' pointer, compile-time and runtime polymorphism, and the implementation of virtual and pure virtual functions. Additionally, it discusses file stream classes, file operations, and provides examples of using manipulators for formatted output.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views11 pages

VPMP Unit 5

This document covers Unit 5 of Basic Object Oriented Programming, focusing on polymorphism, virtual functions, and file handling in C++. It explains the use of the 'this' pointer, compile-time and runtime polymorphism, and the implementation of virtual and pure virtual functions. Additionally, it discusses file stream classes, file operations, and provides examples of using manipulators for formatted output.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Subject Name: Basic Object Oriented Programming Unit No: 5 Subject Code: 4320702

Unit– 5: Polymorphism, Virtual Function and working with Files

5.1 this pointer


 The this pointer holds the address of current object. In other words we can say that this pointer points to
the current object of the class.
 this pointer is used to represent an object that invokes a member function.
 Example: the function call A.max( ) will set the pointer this to the address of the object A.
 Friend functions do not have a this pointer, because friends are not members of a class. Only member
functions have a this pointer.
 Static member functions don't have a this pointer.
 Applications of this pointers are
1) The private variable can be directly inside a member function
Example:
class ABC
{
int a;
public:
void getdata(int x)
{
thisa=x; //private variable a is declared inside function.
}
void print()
{
cout << "a = " <<a << endl;
}

};
void main( )
{
ABC a1;
a1.getdata(50);
a1.print( );
}
Output:
a=50

2) The application of this pointer is to return the object it points to.


return *this;

Example:

#include<iostream.h>
#include<conio.h>

Prepared By: Department of Computer Engineering Page 1


Subject Name: Basic Object Oriented Programming Unit No: 5 Subject Code: 4320702
class person
{
private:
char name[10];
int age;
public:
void getdata( )
{
cout<<”Enter Name and Age :”
cin>>Name;
cin>>age;
}
void putdata( )
{
cout<<”Name:”<<name;
cout<<”Age:”<<age;
}
person & elder (person &p)
{
if (p.age > age)
return p;
else
return *this;
}

};
void main( )
{
person p1,p2;
p1.getdata( );
p2.getdata( );
p1.putdata( );
p2.putdata( );

person& p3=p1.elder(p2);
cout<<” Elder is : “;
p3.putdata( );
getch( );
}
Output:
Enter Name and Age : Sunita 20
Name: Sunita
Age: 20
Enter Name and Age : Anita 18
Name: Anita
Age: 18
Elder is :
Name: Sunita
Age: 20

Prepared By: Department of Computer Engineering Page 2


Subject Name: Basic Object Oriented Programming Unit No: 5 Subject Code: 4320702
5.2 Compile time and runtime polymorphism

 Polymorphism means "many forms".


 In simple words, we can define polymorphism as the ability of a message to be displayed in more
than one form.

5.3 virtual function and pure virtual function

Virtual function
 When we use the same function name in both the base and derived classes, the function in base class
is declared as virtual using the keyword virtual preceding its normal declaration.
 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, rather than the type of the pointer.
 So, by making the base pointer to point to different objects, we can execute different versions of the
virtual function.
 They are mainly used in Runtime polymorphism
 Rules for virtual function

• The virtual function must be members of some class.


• They cannot be static members.
• They are accessed by using object pointers.
• A virtual function can be a friend of another class.
• A virtual function in a base class must be defined, even though it may not be used.
• The prototypes of the base class version of a virtual function and all the derived class versions
must be identical. If two functions with the same name have different prototypes, C++ considers
them as overloaded functions.
• We cannot have virtual constructors, but we can have virtual destructors.
• While a base pointer can point to any type of the derived object, the reverse is not true.
• If a virtual function is defined in the base class, it need not be necessarily redefined in the derived
class. In such cases, calls will invoke the base function.

Prepared By: Department of Computer Engineering Page 3


Subject Name: Basic Object Oriented Programming Unit No: 5 Subject Code: 4320702
Example:
#include<iostream.h>
#include<conio.h>
class base
{
protected:
int b;
public:
base(int b1)
{
b=b1;
}
virtual void display ( )
{
cout<<”b= “<<b;
}
};

class derived: public base


{
protected:
int d;
public:
derived(int b1, int d1):base(b1)
{
d=d1;
}
void display ( )
{
cout<<”b= “<<b;
cout<<”d= “<<d;
}

};

void main()
{
base *b;
base b1(5);
b=&b1;
bdisplay( ); //call display( ) function of base class

derived d1(10,20);
Prepared By: Department of Computer Engineering Page 4
Subject Name: Basic Object Oriented Programming Unit No: 5 Subject Code: 4320702
derived d2(30,40);

b=&d1;
bdisplay( ); //call display( ) function of derived class

b=&d2;
bdisplay( ); //call display( ) function of derived class
}

Output:

b=5
b=10 d=20
b=30 d=40

Pure virtual function


 In the pure virtual function, the function is declared as virtual inside the base class and redefine it in
the derived classes,
 The function inside the base class is used for performing any task.
 It only serves as a placeholder.
 It is also called as a “do-nothing” function.
 It may be defined as follows:
virtual void area( )=0;
 Such functions are called as pure virtual functions.
 A pure virtual function is a function declared in a base class that has no definition relative to the base
class.
 A class containing pure virtual functions cannot be used to declare any objects of its own. And such
classes are called as abstract base classes.
 Example

#include<iostream.h>
#include<conio.h>

class shape
{
protected:
float r;

public:
shape(float r1)
{
r=r1;
}
virtual float area( )=0;
};

Prepared By: Department of Computer Engineering Page 5


Subject Name: Basic Object Oriented Programming Unit No: 5 Subject Code: 4320702
class circle: public shape
{
public:
circle(float f1):shape(r1)
{
}
float area( )
{
return (3.14*r*r);
}
};
class rect: public shape
{
private:
float b;
public:
circle(int r1,int b1):shape(r1)
{
b=b1;
}
float area( )
{
return (r*b);
}
};
void main( )
{
shape *s1,*s2;
s1=new circle(2);
s2=new rect(5,10);
s1->area( );
s2->area( );
getch( );
}

5.4 Introduction to File Stream Classes

 The C++ I/O system contains a hierarchy of classes that are used to define various streams to deal
with both the console and disk file.
 These classes are called as stream classes.
 The stream classes are used for input and output operations with the console unit.
 These classes are declared in the header file iostream.
 The ios class is the base class for istream and ostream.
 The istream and ostream classes are base classes for iostream.
 The class ios is declared as the virtual base class so that only one copy of its members is inherited by
the iostream.
 The class ios provides the basic support for formatted and unformatted I/O operations .

Prepared By: Department of Computer Engineering Page 6


Subject Name: Basic Object Oriented Programming Unit No: 5 Subject Code: 4320702

 ios class:
• It provides the input & output facilities.
• It contains a pointer to a buffer object.

 istream class:
• Inherits the properties of ios.
• Declares input functions such as get( ), getline( ) and read( )
• Contains overloaded extraction operator >>

 ostream class:
• Inherits the properties of ios.
• Declares input functions such as put( ) and write( )
• Contains overloaded extraction operator <<

 iostream class:
• It inherits the properties of ios, istream and ostream through multiple inheritances and thus
contains all the input and output functions.

 streambuf:
• Provides an interface to physical devices through buffers.
• Acts as a base for filebuf class used ios files.

Prepared By: Department of Computer Engineering Page 7


Subject Name: Basic Object Oriented Programming Unit No: 5 Subject Code: 4320702
5.5 Opening and closing a file- File opening modes.

 File handling is used to store data permanently in a computer. Using file handling we can store our
data in secondary memory
 File Operations
1. Creating a new file. (fopen with mode “a” or “w”)
2. Opening an existing file. (fopen)
3. Reading from or writing information to the file. (fscanf or fgets, fprintf or fputs)
4. Closing the file. (fclose).

Working with files


 When working with the files, there is a need to declare a pointer of the type file. This file-type pointer
is needed for communication between the file and the program.
 Syntax:
file *file_pointer;

 Example:
file *fptr;

Opening a file
 Opening a file is done using the fopen() function in the header file stdio.h.
 Syntax:
file_pointer = fopen(“file_name”, “mode”);

 Example:
fptr= fopen(“D:\\myfolder\\file1.txt”, “w”);
 File Opening modes in C:

Mode Meaning of Mode During Inexistence of file

r Open for reading. If the file does not exist, fopen( ) returns NULL.

Open for reading in binary


If the file does not exist, fopen( ) returns NULL.
rb mode.

If the file exists, its contents are overwritten. If the file does
Open for writing.
w not exist, it will be created.

Open for writing in binary If the file exists, its contents are overwritten. If the file does
wb mode. not exist, it will be created.

Data is added to the end of the file. If the file does not exist,
Open for append.
a it will be created.

Prepared By: Department of Computer Engineering Page 8


Subject Name: Basic Object Oriented Programming Unit No: 5 Subject Code: 4320702

Open for append in binary Data is added to the end of the file. If the file does not exist,
ab mode. it will be created.

Reading from or writing information to the file

fgets( ):
 The fgets() function in C++ reads a specified maximum number of characters from the given file stream.
 On success, the fgets() function returns str and on failure it returns null pointer.

 Syntax:

fgets(char* str, int count ,FILE* stream);

 Example:

fgets(str,10, fptr);

fputs( )
 The fputs() function in C++ writes a string completely except the terminating null character to the given
output file stream.

 Syntax:

fputs(char* str, FILE* stream);

 Example:

fputs(“HELLO” , fptr);

Closing a file

 The file should be closed after reading or writing. Closing a file is performed using the fclose() function.

 Syntax:
fclose(file_pointer);

 Example:
fclose(fptr);

Prepared By: Department of Computer Engineering Page 9


Subject Name: Basic Object Oriented Programming Unit No: 5 Subject Code: 4320702
Program: Write a program using manipulators Like setw( ), setprecision( ), setfill( ),
setiosflags( ), etc.
#include <iostream.h>
#include <iomanip.h>
void main()
{
cout<<" setw() ..............\n";
cout<< setw(10) <<11<<"\n";
cout<< setw(10) <<2222<<"\n";
cout<< setw(10) <<4<<"\n";

cout<<"setw() & setfill() ...\n";


cout<< setfill('0');
cout<< setw(10) <<11<<"\n";
cout<< setw(10) <<2222<<"\n";
cout<< setw(10) <<4<<"\n";

cout<<” setprecision …”;


float a,b,c;
a = 5;
b = 3;
c = a/b;
cout << setprecision (1) << c << endl;
cout << setprecision (2) << c << endl;
cout << setprecision (3) << c << endl;

cout<<” setiosflags …“
int value;
cout << “ enter a number \n”;
cin >> value;
cout << setiosflags (ios : : showbase) ;
cout << setiosflags (ios : : dec) ;
cout << “ decimal = “ << value << endl;
cout << setiosflags (ios : : hex) ;
cout << hexadecimal = “ << value << endl ;
cout << setiosflags (ios : : oct) ;
cout << “ octal = “ << value << endl ;
}

Prepared By: Department of Computer Engineering Page 10


Subject Name: Basic Object Oriented Programming Unit No: 5 Subject Code: 4320702

Output:

setw() ..............
11
2222
4

setw() & setfill()...


0000000011
0000002222
0000000004

setprecision …
1.7
1.67
1.667

setiosflags …
enter a number
10
decimal = 10
hexadecimal = 0xa
octal = 012

Prepared By: Department of Computer Engineering Page 11

You might also like