Virtual Fucntion
Virtual Fucntion
Title: Create three classes: polygon (base class), rectangle and triangle (derived classes) having
the same members: width, height, and functions set values and area. Write a C++ program using
run time polymorphism to implement it. (Make polygon class as abstract class.)
Description:
An abstract class is like a blueprint for creating other classes in programming. Think of it as a
general concept, such as a Vehicle. You can't create a Vehicle by itself; instead, you define
what a vehicle should do—like moving or stopping—but you leave out the details. Other classes,
like Car or Bike, would inherit from this abstract class and fill in those specifics. This approach
helps keep your code organized and ensures that all vehicles share some common features while
allowing each type to behave in its unique way.
On the other hand, virtual functions are like invitations for subclasses to provide their unique
responses to a shared action. For example, if you have a virtual function called startEngine()
in your Vehicle class, both Car and Bike can have their own ways of starting the engine. When
you call startEngine() on a Vehicle reference pointing to a Car, the program knows to use the
Car's version of that function. This flexibility is really powerful; it lets you write code that can
handle different types of vehicles while ensuring that each one operates according to its specific
rules, making your programs much more adaptable and easier to manage.
class Polygon {
protected:
float width, height;
public:
public:
void setValues(float w, float h) override {
width = w;
height = h;
}
int main() {
polygon1->setValues(5.0, 4.0);
cout << "Area of Rectangle: " << polygon1->area() << endl;
polygon2->setValues(5.0, 4.0);
cout << "Area of Triangle: " << polygon2->area() << endl;
delete polygon1;
delete polygon2;
PP Lab PRN:24070122505
return 0;
}
in C++
Practice programs: C++ program program to print student information using virtual
function.