Written by Sai Sandeep Thota on March 23, 2013 in C++ > Programming

C++ Program to Convert Celsius to Fahrenheit, KM to Mt, Hrs to Sec using Virtual Functions

GET ALERTS:

Get our Latest updates delivered to your mailbox!

Today we will discuss one of the most important features of Object Oriented Programming, i.e., Virtual Functions. In the following program we are creating a base class with a virtual function convert() in it. Then we are inheriting the base class in derived classes, so that we use all the functions of the base class in the derived classes. If you are familiar with the inheritance concepts, you would easily understand these topics.

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

class conversion {
	public:
	virtual void convert() {
		int c;
		cout<<"Enter Celcius Value:";
		cin>>c;
		int farenheit = (c*1.8)+32;
		cout<<"Celcius to Fareinheit "<<c<<"C = "<<farenheit<<"F";
	}
};

class km:public conversion {
	public:
	void convert() {
		int km;
		cout<<"\nEnter Kilometers Value:";
		cin>>km;
		unsigned meters = km * 1000;
		cout<<km<<" = "<<meters<<" Meters";
	}
};

class sec:public km {
	public:
	void convert() {
		int hour;
		cout<<"\nEnter number of Hours:";
		cin>>hour;
		unsigned int seconds = hour*60*60;
		cout<<hour<<" hour(s) = "<<seconds<<" seconds";
	}
};

void main() {
	conversion ob, *ptr;
	km ob1;
	sec ob2;
	clrscr();
	ptr = &ob;
	ptr->convert();
	ptr = &ob1;
	ptr->convert();
	ptr = &ob2;
	ptr->convert();
	getch();
}

Output:
virtual_functions

{ 1 comment… read it below or add one }

eswar April 14, 2013 at 5:30 pm

thanxz sandeep thota
nice work

Reply

Leave a Comment

Previous post:

Next post: