[CSI] Class Destructors

Mikhail Nesterenko mikhail at cs.kent.edu
Fri Dec 9 17:24:23 EST 2016


> 
> Should destructors be reserved for deallocating dynamic memory or is it
> stylisitically appropriate to include other actions or functions?
> 
> Say,
> 
> #include <iostream>
> 
> class MyClass {
>     public:
>         MyClass( int ) : size( n ) { }
>         ~MyClass( ) { Goodbye( ); }
>         int GetSize( ) { return size; }
>     private:
>         int size;
>         void Goodbye( ) const { std::cout << "End of scope."; }
> };
> 
> int main( ) {
>     MyClass ob(5);
>     // do stuff
> }
> 
> Or is this considered inelegant and it is preferred that methods always be
> explicitly called? (excluding Big Three and constructors)


Destructor is specifically designed for memory deallocation when the
object of this class goes out of scope. It is considered poor style to
do anything else rather than deallocate dynamic memory in the
destructor. The printout in the destructor is usually used to
demonstrate its implicit invocation at the end of variable scope.

By the way, C++ syntax allows explicit destructor invocation. However,
this is not recommended.

Thanks,
--
Mikhail


More information about the cs13001 mailing list