A community for students.

Here's the question you clicked on:

55 members online
  • 0 replying
  • 0 viewing


  • one year ago

what is the usage of constructors and destructors in c++?

  • This Question is Open
  1. rhr12
    • one year ago
    Best Response
    You've already chosen the best response.
    Medals 0

    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; }

  2. Not the answer you are looking for?
    Search for more explanations.

    • Attachments:

Ask your own question

Sign Up
Find more explanations on OpenStudy
Privacy Policy

Your question is ready. Sign up for free to start getting answers.

spraguer (Moderator)
5 → View Detailed Profile

is replying to Can someone tell me what button the professor is hitting...


  • Teamwork 19 Teammate
  • Problem Solving 19 Hero
  • You have blocked this person.
  • ✔ You're a fan Checking fan status...

Thanks for being so helpful in mathematics. If you are getting quality help, make sure you spread the word about OpenStudy.

This is the testimonial you wrote.
You haven't written a testimonial for Owlfred.