Professional Documents
Culture Documents
ng C S C 2 4 1
Class: BEE-3C
class base
{
public:
virtual void iam()
{
cout << "base\n";
}
};
int main(){
base b;
child1 c1;
child2 c2;
//After removing Virtual from base class function, only that function was executed which belonged to
the class of pointer object.
Output:
class Shape
{
public: double a,b;
void get_data ()
{
cin>>a>>b;
}
virtual void display_area () = 0;
};
int main()
{
Triangle t;
Shape *st = &t;
cout<<"Enter base and altitude: ";
st->get_data();
st->display_area();
Rectangle r;
Shape *sr = &r;
cout<<"Enter length and breadth: ";
sr->get_data();
sr->display_area();
return 0;
}
Output:
Home TASKS
Home Task 6.1:
// Virtual function practical example.
#include <iostream>
using namespace std;
class convert {
protected:
double val1; // initial value
double val2; // converted value
public:
convert(double i) {
val1 = i;
}
double getconv() { return val2; }
double getinit() { return val1; }
virtual void compute() = 0;
};
// Liters to gallons.
class l_to_g : public convert {
public:
l_to_g(double i) : convert(i) { }
void compute() {
val2 = val1 / 3.7854;
}
};
// Fahrenheit to Celsius
class f_to_c : public convert {
public:
f_to_c(double i) : convert(i) { }
void compute() {
val2 = (val1-32) / 1.8;
}
};
int main()
{
convert *p; // pointer to base class
l_to_g lgob(4);
f_to_c fcob(70);
// use virtual function mechanism to convert
p = &lgob;
cout << p->getinit() << " liters is ";
p->compute();
cout << p->getconv() << " gallons\n"; // l_to_g
p = &fcob;
cout << p->getinit() << " in Fahrenheit is ";
p->compute();
cout << p->getconv() << " Celsius\n"; // f_to_c
return 0;
}
Output:
Critical Analysis / Conclusion:
In this lab we learn about the concepts of virtual functions and polymorphism, late/dynamic
binding, abstract class and pure virtual functions. Polymorphism is the ability of objects of
different types to respond to functions of the same name. The user does not have to know the
exact type of the object in advance. Polymorphism enables to “program in general” rather than
“program in specific”.
A function that appears to exist in some part of a program but does not exist really is called
virtual function. Virtual functions are used to implement polymorphism.
The early binding occurs when everything required to call a function is known at compile time.
The late binding occurs when some information to call a function is decided at execution time.
An abstract class is a class that can only be a base class for other classes. We cannot create an
instance of an abstract class. Instead, it contains operations that are common to all of its derived
classes.