Constructors help.

I know how to build a constructor, but I don't know when to utilize it. The entire concept for me is confusing. Could anyone here please explain how Constructors and Deconstructors work and why.

Thanks.

The constructor is called when an object is created. Its main purpose is to initialize member variables.

The destructor is called when the object is destroyed. Often you don't need to put anything in the destructor but if the class has made dynamic memory allocations (using new) you probably want to free the memory here (using delete).
an example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
using namespace std;

class T {
	private:
		int *pt;
	public:
		T (int x) // constructor
		{
			cout << "constructor initiated.\n";
			pt = new int[x];
			for (int i=0; i<x; i++)
			{
				pt[i] = i*2;
			}
		}
		
		~T ()  // destructor
		{
			delete[] pt; // delet allocated memory
			cout << "allocated memory deleted.\n";
		}
		
		int show(int x)
		{
			return pt[x];
		}		
};

int main()
{
	T ob1(10); // 10 goes to constructor
	T ob2(20); // 20 goes to constructor
	
	for (int i=0; i<20; i++)
		cout << ob2.show(i) << " ";

    cout << "\nend of main() \n\n";
return 0;
}
Last edited on
Hey bro I was confused like you and no one could explain me why should I use them.
I highly suggest you to use the book : c++ through game programming.micheal dawson.
What I like in this book, even if it's short, is that it gives you an example of everything you learn in a game.so at first I didn't understand constructors.and now I will tell you in a game example how you can use it. Suppose you want to create an enemy in a game.
The enemy should start with a specified attack damage.
You assign the attack damage in the constructor and every time an enemy is created it will have the attack damage you specified in the constructor.
Another example is that you want to create a virtual pet game.
Each time a pet will born it must have a hunger level, fun level, and mood.
You assign these values in the constructors for each time a pet is creared it will have these values.
For a code example kik me : wu_lebanon ir whatsapp :0096171067522.
I cannot give you code on my phone now.
Download this book it will help you so much.
Hope it helped :)
Thanks everyone!

Especially to you, xxgixx, my main purpose of learning C++ is to become a game developer, thanks for seeing eye to eye with me and giving examples. I think I understand what a Constructor is.

Thanks everyone :)
Topic archived. No new replies allowed.