Constructor/Destructor

I'm just learning about classes and I get it for the most part (only about halfway done the class chapter at the moment.) However I do have a question about constructor/destructor that is a little confusing to me..From what this book is telling me there are two ways to write this class...

Without constructor/destructor
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

class Cat
{
public:
	int GetAge();
	void SetAge(int age);
	void Meow();
private:
	int itsAge;
};

// GetAge public accessor function
// returns private value of itsAge
int Cat::GetAge()
{
	return itsAge;
}

// SetAge public accessor function
// sets private value of itsAge
void Cat::SetAge(int age)
{
	itsAge = age;
}

// Simply prints "meow" to screen
void Cat::Meow()
{
	cout << "Meow." << endl;
}



With constructor/destructor
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
42
class Cat
{
public:
	Cat(int initialAge); //Constructor
	~Cat(); //Destructor
	int GetAge();
	void SetAge(int age);
	void Meow();
private:
	int itsAge;
};

//Constructor function
Cat::Cat(int initialAge)
{
	itsAge = initialAge;
}

//Destructor function
Cat::~Cat()
{
}

// GetAge public accessor function
// returns private value of itsAge
int Cat::GetAge()
{
	return itsAge;
}

// SetAge public accessor function
// sets private value of itsAge
void Cat::SetAge(int age)
{
	itsAge = age;
}

// Simply prints "meow" to screen
void Cat::Meow()
{
	cout << "Meow." << endl;
}


Now in the main function the author provided to show an example of this, he simply called..
 
Cat Frisky(5);


instead of..
1
2
Cat Frisky;
Frisky.SetAge(5);


I just really don't understand the point of all this? Can someone explain to me if there's more to constructor/destructor to this because the way it's explained in this book isn't very helpful and I don't see what the point is if it simply saves you a line or two in the main function at the cost of several lines in the class added...
Last edited on
The constructor is a function that is called on the "construction" of an object, i.e the declaration. Cat Frisky(5); calls the Cat(int initialage) function for the new object Frisky. Destructors are then same, except they are called when an object is "destroyed", i.e goes out of scope or explicitly destructed.
Constructors are useful because they let you initialize the state of an object whenever one is created. This gives you a guarantee that an object is always in a "known" state. That way you don't get left with objects that haven't been set up yet.

Granted the above example isn't really very practical, but it's not easy to come up with a simple example of where a constructor is really useful. They're more important with complicated classes.

Here's an example of why ctors/dtors can be important. Let's say you have a class that mimics a variable size array... like a vector:

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
class IntArray
{
private:
  int* data;
  int size;

public:
  void Resize(int newsize)  //  change the size of the array
  {
    int* buf = new int[newsize];  // create the new buffer
    int numtocopy = std::min(size,newsize);  // the number of elements to copy
    std::copy(data,data+numtocopy,buf);  // copy the old data to the new buffer
    delete[] data;  // delete the old buffer
    data = buf;  // make the new buffer our data buffer
  }

  int& operator [] (int index)
  {
    return data[index];
  }
};

//================
//  now that we have this class, let's try to use it.

int main()
{
  // let's make an array with 10 elements:
  IntArray array;
  array.resize(10);  // EXPLODE - see below
}


The resize call would explode here because 'IntArray::data' has never been initialized, so it's a bad pointer. Trying to delete a bad pointer could corrupt memory, or just make the program crash.

We could fix that with some kind of "initialize" funciton. Like this:

1
2
3
IntArray array;
array.initialize();  // initialize all our stuff
array.resize(10);  // so that this is no problem 


But that makes the class a pain to use. What if you forget to do that one time?

The better alternative is to make a constructor. Since they are guaranteed to be called whenever the object is created, you can make sure it's always initialized:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class IntArray
{
 //...
public:
  IntArray()
  {
    data = 0;
    size = 0;
  }
};

int main()
{
  IntArray array;  // now this is initialized
  array.resize(10);  // so this is no problem!
}



The next problem here... is what happens when our array dies? We never delete the memory buffer. This will cause the program to leak memory. Therefore, writing a destructor is important to make sure the memory get properly cleaned up:

1
2
3
4
5
6
7
8
9
class IntArray
{
//...
public:
  ~IntArray()  // when the object dies...
  {
    delete[] data;  // clean up our allocated memory
  }
};




That's why ctors and dtors can be useful.

Note the above class isn't practical. There are other issues regarding copying the array, but I'll save that for another day.
The book you are reading seems very misleading, in fact. I don't think there is ever an equivalent to a destructor, for example.

To explain: Destructors are pieces of code (functions) that are always called when the object goes out of scope. This is for objects in the stack only. For objects in the heap, they are called when the object is deleted. If you don't know about stack and heap, not to worry right now. Know just this: A destructor is guaranteed to run on object destruction. A "destructor-less" class has no code that is guaranteed to run (even in the event of a runtime error), so any potential cleanup tasks are not performed. I don't see how anyone can say that a class can be written without a destructor and be equivalent to one with a destructor, unless the destructor function is empty.

Now let's move on to the point of using constructors instead of using set accessors: Performance. If that book of yours is any good, it should have told you that ALL classes have:

-A parameterless constructor.
-A copy constructor.
-An assignment operator.

I think those 3. This means that if you don't explicitly write a constructor, one is provided for you. Same for the copy constructor; same for the assignment operator.

So by NOT writing your own constructor and using the 2-line approach (with the set accessor), you are being slower than using the version with the constructor.

Why? Well, that's a bit much to post in a forum's answer. Keep reading. Maybe the book explains.
I do know what stack, heap, etc all are as it was explained in the book. I do know that if you don't explicitly write your own constructor/destructor then one is provided for you by the compiler. What I was asking is if there was a specific purpose of writing your own constructor (other than assigning variables upon making a new instance of the class.) Your answers and the rest of that chapter has helped me understand this a little further.

I just finished the chapter on classes and structures and I basically understand what they are, how to manipulate them, how to use them and all that good stuff. However, I still am a little confused because everything up to classes so far in this book has been EXTREMELY easy for me lol. So I think I will just spend a few more days playing around with classes (no point in structures as they're the same except everything is public by default instead of private) until I get a 100% grasp on this. Then I will move on.. :D
EXTREMELY easy for me lol

Good. For some reason there are always some people who struggle with that part already. The hard is actually how to properly use OOP for clean designs.
the Book which you are reading SUCKS!
Learn C++ in 21 days... isn' it?
once again -->THIS BOOK SUCK!

i recomend you Bjarne Stroustrup's book or anythig else.
there is no way to get even an overwiev of C++ language within 21 days, at least not with book you curently reding.

I have start learn C++ with same book (C++ in 21 days) after I switch to another book I realised what fool I was :/
learn like an idiiot but don't get nothing, I was very confused and disapointed.
hope you will get same meaning once you change book.
^Thinking of this I think....

http://norvig.com/21-days.html
I've read this before a week I think.
it's good to start there before choosing which language to learn an more.

best site on the net
I think I have a way to show that constructors are important. I haven't yet learned Destructors however I've used constructors in my inventory system for my game. It's something like this

1
2
3
4
5
6
7
struct Item{
	string Name;
	int buyPrice;
	int sellPrice;
};

Item Copper = {"Copper",10,5,};


The line Item Copper = {"Copper",10,5,}; creates a structure that contains all of the variables that the original had. struct Item merely acts as a base structure for the others to be created. If you haven't learned yet a structure is merely a class with the values always initialized as public.
constructors, destructor and copy constructors are inportant mostly when dynamic alocation is used.
in static alocation of class members only overloaded constructors are used- mostly, or default constructor.
Not true sasanet. The copy constructor is used with stack objects even more often than it is used with dynamic allocation.
Thanks for all the advice/help everyone. For those talking bad about my book, so far I am really liking it. There are definitely parts I have to read over 2-3 times before I can grasp the concept but that can be said with just about any book. Right now I'm on day 6 of the book (3rd day reading it) and I've actually learned quite a bit. Also I realize learning a programming language in 21 days is ridiculous, but it's just the title and it's not as though any other book would take longer than 21 days to read either. However if anyone wants to recommend a good book for when I'm done this one, I am most likely going to read 1-2 more after this one.
Last edited on
Topic archived. No new replies allowed.