Startertutorials Blog
Tutorials and articles related to programming, computer science, technology and others.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.

Categories: Classes and Objects. No Comments on Cpp program to illustrate the use of constructor and destructor
2.7
(10)

In this article we will learn to implement a Cpp program to illustrate the use of constructor and destructor. A C++ program is provided below to demonstrate the use of constructor and destructors. Program is as follows:

#include <iostream>
using namespace std;
class Distance
{
	private:
		int feet;
		int inches;
	public:
		Distance() {}
		Distance(int f, int i)
		{
			feet = f;
			inches = i;
		}
		void get_distance()
		{
			cout<<"Distance is feet= "<<feet<<", inches= "<<inches<<endl;
		}
		void add(Distance &d1, Distance &d2)
		{
			feet = d1.feet + d2.feet;
			inches = d1.inches + d2.inches;
			feet = feet + (inches / 12);
			inches = inches % 12;
		}
		~Distance()
		{
			cout<<"Distance object destroyed"<<endl;
		}
};
int main()
{
	int f1, in1, f2, in2;
	cout<<"Enter feet: ";
	cin>>f1;
	cout<<"Enter inches: ";
	cin>>in1;
	cout<<"Enter feet: ";
	cin>>f2;
	cout<<"Enter inches: ";
	cin>>in2;
	Distance d1(f1, in1);
	Distance d2(f2, in2);
	Distance d3;
	d3.add(d1, d2);
	d3.get_distance();
	return 0;
}

 

Input and output for the above program are as follows:

Enter feet: 3
Enter inches: 8
Enter feet: 4
Enter inches: 9
Distance is feet= 8, inches= 5
Distance object destroyed
Distance object destroyed
Distance object destroyed

 

How useful was this post?

Click on a star to rate it!


Subscribe to our monthly newsletter. Get notified about latest articles, offers and contests.


We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Suryateja Pericherla

Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.

He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.

He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.

Leave a Reply

Your email address will not be published. Required fields are marked *