Question

C++ Question. Please answer the following question and provide a short explanation, thank you. When does...

C++ Question. Please answer the following question and provide a short explanation, thank you.

When does a class need to provide a destructor? Why?

0 0
Add a comment Improve this question Transcribed image text
Answer #1

A destructor can be defined as a member function of the class that is executed whenever an object of it's class goes out of scope. It is required to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. The destructor is of the same name as that of the class prefixed by ~ (tilde) symbol. Eg:

class Student { public: //Constructor Student() { cout<<"Constructor is called"<<endl; } //Destructor ~Student(){ cout<<"Destructor is called"<<endl; } //Member function void display(){ cout<<"Student Details"<<endl; } };

The output we get for the program is:

Constructor is called Student Details Destructor is called

Destructor is called at the last when we need to delete the object created. A destructor takes no arguments and has no return type. They cannot be declared const, volatile or static.

If no user-defined destructor exists for a class then the compiler implicitly declares one. This implicitly declared destructor is an inline public member of its class.

Add a comment
Know the answer?
Add Answer to:
C++ Question. Please answer the following question and provide a short explanation, thank you. When does...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT