CSC166 Object Oriented Programming

Object Oriented ProgrammingTU Board 2080 (new course)

What is destructor? List its characteristics. Explain the use of default copy constructor with an appropriate example.

10

Answer

A destructor is a special member function that is called automatically when an object is destroyed, for example when it goes out of scope or is deleted with delete. It is used to release resources such as dynamic memory or open files.

~ClassName() { /* clean-up */ }

Characteristics of a destructor

  • Its name is the class name preceded by a tilde ~.
  • It has no return type, not even void.
  • It takes no arguments, so it cannot be overloaded; a class has only one destructor.
  • It is called automatically; it is not called explicitly in normal code.
  • Objects are destroyed in the reverse order of their creation.
  • It should be declared in the public section.
  • It can be virtual (needed when deleting a derived object through a base-class pointer).

Default copy constructor

If a class does not define a copy constructor, the compiler supplies a default copy constructor. It copies each data member of the source object into the new object (a member-wise, shallow copy). This is enough for classes that contain only ordinary values.

#include <iostream>
using namespace std;

class Box {
    int length, width;
public:
    Box(int l, int w) : length(l), width(w) {}
    ~Box() { cout << "Box " << length << "x" << width << " destroyed\n"; }
    void show() { cout << "Box " << length << "x" << width << endl; }
};

int main() {
    Box b1(4, 3);
    Box b2 = b1;       // default copy constructor copies length and width
    b1.show();
    b2.show();
    return 0;          // destructors run for b2, then b1
}

Output

Box 4x3
Box 4x3
Box 4x3 destroyed
Box 4x3 destroyed

If a class holds a pointer to dynamic memory, the default copy constructor copies only the pointer. Both objects then point to the same memory, and both destructors would free it. Such classes must define their own copy constructor that makes a deep copy.

Discussion

Loading…

More Object Oriented Programming questions

All Object Oriented Programming old questions