Constructor & Destructor

Please, I don't understand how to implement a constructor, a copy constructor et and destructor.
I've seen some examples but they are so easy, I would really like to know a good way to implement them.
thx a lot for your help
A very common use for constructors/destructors is to implement RAII (Resource Acquisition is Initialization) look it up on google..

lets do a basic example - say you needed an array of variable size

normally you would have to do

int x;
cin >> x;
int array = new int[x];

but if you didn't remember to call delete later in the program

delete [] array;

you would have a memory leak - maybe not a big deal here but if this happens millions of times throughout a program it will bog down the computer until the program exits..

solution?

make a class that makes a variable size array for you and use the constructor/destructor to allocate and delete the memory.

class myArray
{
public:
myArray(int size): //constructor (no return type and same name as class)
{
arr = new int[size];
}

~myArray()
{
delete [] arr;
}
private:
int arr[];
};

now to make a variable sized array you would say

int x;
cin >> x;
myArray array(x);

and no matter what when array goes out of scope the destructor will be called and it will delete the dynamically allocated memory.

Look in to RAII if you want to learn more ie why you would need a copy constructor in this scenerio
A constructor is nothing more than a "function" that gets called when an object is constructed. It's purpose is to
"initialize" the contents of the object. (Recall that fundamental types such as int,bool, float, etc are not implicitly
initialized by the compiler). Keep in mind that there is a difference between initialization and assignment.
Almost all newbies use assignment because they are not familiar with initializer list syntax.

A destructor is nothing more than a "function" that gets called when an object is destroyed. It's purpose is to
"clean up" after the object. Usually, this means freeing any memory allocated by the object.

Here is dreamincolor's example done correctly:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class MyIntArray
{
  public:
    // The default constructor should initialize the object to an array of zero elements (what else???)
    MyIntArray() : numElements(), array() {}

    // Here is a constructor that makes an array of N copies of V
    MyIntArray( size_t n, int v ) : numElements( n ), array( new int[ n ] )
        { std::fill( array, array + n, v ); }

    // The destructor should "clean up" -- usually, this means deallocating memory that the object allocated
    ~MyIntArray() { delete array; }  // C++ standard guarantees that delete of a NULL pointer is OK.

  private:
     size_t numElements;
     int*    array;
};


Note: some syntax help. Here is a detailed explanation of one of the constructors above.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Here is a constructor that makes an array of N copies of V
MyIntArray( size_t n, int v )   
    :  // the colon here indicates that what follows is an initializer list.  
       // you can initialize any or all of the data members of the class this way.
       // you must keep the ordering of these the same as the order of declaration of the members in the class
       //   because the C++ standard guarantees you that members are initialized in the order of declaration,
       //   regardless of the order in which you put them here:
    numElements( n ),   // This is initializer list syntax.  It is the same as saying "numElements = n;" except
                                   // that it has to be like I wrote it.  Essentially, all initializers in this list have to look
                                   // like constructor calls.
    array( new int[ n ] )
{ 
    // All of the initializers are run BEFORE even the first line of code in the body of the constructor.  Most objects
   // can be completely initialized rather easily by the initializer list such that the body of the constructor can remain
   // empty.  It should be your goal to keep the body empty and do all the work in the initializer list, but I'm just
   // presenting a more comprehensive example here.  I could have also done this in the initializer list via a function
   // call.
    std::fill( array, array + n, v );   // just fills the array with v
}


Topic archived. No new replies allowed.