what is the usage of constructors and destructors in c++?
Constructors and destructors are fundamental to the concept of classes in C++. Both constructor and destructor are more or less like normal functions (but with some differences) that are provided to enhance the capabilities of a class. Constructor, as the name suggests is used to allocate memory (if required) and construct the objects of a class while destructor is used to do the required clean-up when a class object is destroyed. In this article, we will study the concept of constructors and destructors through working examples. If you are new to C++, you should first understand the concept of C++ classes. Constructors and Destructors Let’s understand the concept of constructors and destructors through this example : #include<iostream> class country { public: country() { std::cout<<"\n Constructor called \n"; } void setNumOfCities(int num); int getNumOfCities(void); ~country() { std::cout<<"\n Destructor called \n"; } private: int num_of_cities; }; void country::setNumOfCities(int num) { num_of_cities = num; } int country::getNumOfCities(void) { return num_of_cities; } int main(void) { country obj; int num = 5; obj.setNumOfCities(num); num = obj.getNumOfCities(); std::cout<<"\n Number of cities is equal to "<<num; return 0; }
Join our real-time social learning platform and learn together with your friends!