Professional Documents
Culture Documents
Assignment 03 (Oop TH)
Assignment 03 (Oop TH)
Question No: 2
a) Write a program that shows the use of read() and write() to handle file
I/O involving objects.
#include <iostream>
#include <fstream>
int main(){
char text[200];
fstream file;
cin.getline(text, sizeof(text));
// Writing on file
file.close();
return 0;
b) The keyword ‘virtual’ can be used for functions as well as classes in C++.
Explain the two different uses. Give an example each.
A virtual function is a member function which is declared within a base class and is re-defined
(overridden) by a derived class. When you refer to a derived class object using a pointer or a
reference to the base class, you can call a virtual function for that object and execute the
derived class’s version of the function.
Virtual functions ensure that the correct function is called for an object, regardless
of the type of reference (or pointer) used for function call.
They are mainly used to achieve Runtime polymorphism
Functions are declared with a virtual keyword in base class.
The resolving of function call is done at runtime.
#include<iostream>
using namespace std;
base {
public:
virtual void print()
{
cout << "print base class\n";
}
void show()
{
cout << "show base class\n";
}
};
class derived : public base {
public:
void print()
{
cout << "print derived class\n";
}
void show()
{
cout << "show derived class\n";
}
};
int main()
{
base *bptr;
derived d;
bptr = &d;
// Virtual function, binded at runtime
bptr->print();
// Non-virtual function, binded at compile time
bptr->show();
return 0;
}
class Distance {
private:
int meter;
// friend function
Distance() : meter(0) {}
};
int addFive(Distance d) {
d.meter += 5;
return d.meter;
int main() {
Distance D;
return 0;
// forward declaration
class ClassB;
class ClassA {
private:
int numA;
public:
ClassA() : numA(12) {}
};
class ClassB {
private:
int numB;
public:
ClassB() : numB(1) {}
int add() {
ClassA objectA;
};
int main() {
ClassB objectB;
#include <iostream>
using namespace std;
// Template declaration
template <class T>
// Template overloading of function
void display(T t1)
{
cout << "Displaying Template: "
<< t1 << "\n";
}
// Template overloading of function
void display(int t1)
{
cout << "Explicitly display: "
<< t1 << "\n";
}
// Driver Code
int main()
{
// Function Call with a
// different arguments
display(200);
display(12.40);
display('G');
return 0;
}
e) Define a class template Pair which can have a pair of values. The type of
the values is the parameter of the template. Define a member function
Add() which adds the two values and returns the sum.
#include <iostream>
// Class template
class Number {
private:
// Variable of type T
T num;
public:
T getNum() {
return num;
};
int main() {
Number<int> numberInt(7);
// create object with double type
Number<double> numberDouble(7.7);
return 0;