Jump to content
  • Advertisement
Sign in to follow this  
Anexa85

C++ Constructors and Destructors

This topic is 3720 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm going through Sams Teach Yourself C++ in 21 days and reached the part about how to use constructors and destructors in classes. It doesn't seem to really explain it although it does say that all objects must be constructed and destructed. I was just wondering why constructors and destructors are useful. this might be a silly question but I just can't understand why they are necessary. Thanks!

Share this post


Link to post
Share on other sites
Advertisement
Since you can declare variables but not intialize them in the class declaration it is necassary to use the constructor to do that.

When you have a variable declared in a class you can't give it a default value, so you have the class constructor, which is automatically called when you create an object of the type of that class, give the variable its initial value.

class Test
{
private:
Test();
int I;
};

Test::Test()
{
I=4;
}

sorry if syntax is wrong but this is the basic idea, there is another use involving the 'new' keyword and the destructor but I cant remember the case.

Share this post


Link to post
Share on other sites
(Note: This page probably deals with constructors in greater depth that I'm going to.)

Constructors have a variety of uses in C++ programming. In the most basic terms they are used to "initialize" (construct) and "shutdown" (destruct) objects safely and intuitively. You can use them to simply initialize variables or you can use them for much more. As a simple example, let's consider this problem:

Imagine you, for whatever reason, want to wrap up file reading and writing interface in a class. You COULD do something like this:

class TextFile {
private:
//FileHandle myfile; PSEUDO CODE
public:
void open(string filename) {
/* PSEUDO CODE
myfile = open_file_in_text_mode(filename);
*/

}

string readline() {
/* PSEUDO CODE
return read_line_from_file(myfile);
*/

}

void close() {
/* PSEUDO CODE
close_file(myfile);
*/

}
}



In this case to open a file you my write something like this:

TextFile mytextfile;
mytextfile.open("example.txt");
mytextfile.readline(); //This is an example, so we'll just discard the string
mytextfile.close();



While there's nothing inherently wrong with this approach, if you were to forget to "open" or "close" the file, there would be trouble. [smile] Since we want to avoid trouble and make our programming experience as easy as possible, let's consider a different solution that uses constructors and destructors:

class TextFile {
private:
//FileHandle myfile; PSEUDO CODE
public:
TextFile(string filename) { //Constructors and destructors have no return type
/* PSEUDO CODE
myfile = open_file_in_text_mode(filename);
*/

}

string readline() {
/* PSEUDO CODE
return read_line_from_file(myfile);
*/

}

~TextFile() {
/* PSEUDO CODE
close_file(myfile);
*/

}
}



Not much changed, did it? [smile] By simply substituting a constructor and destructor for our "open" and "close" functions, we can now write this code to use our class:

TextFile mytextfile("example.txt");
mytextfile.readline();



Notice that we opened the file at the same time we created the instance, ensuring that we can never attempt to read from the file before it's opened. But what about closing the file you ask?

Since the instance was allocated for us by C++ (as opposed to being created with the "new" keyword), C++ will take care of destroying it and also have the courtesy to call our destructor just before it does so, ensuring that the file is closed when the program exits or the instance is otherwise destroyed.


This is just one of the many ways that you can use constructors and destructors, for more information you might consider having a look at one of the many resources available on google. [smile]

Edit: Small changes for clarity.

Share this post


Link to post
Share on other sites
Also, if you have a reference or const members in your class they must be initialized. The only way to initialize them is with a constructor, specifically in the constructor's initialization list.

class Foo
{
const int a;
float& b;
public:
Foo(const int a, float& b) : a(a), b(b){...}
...
};





Also, constructors also take care of implicit conversion / copy construction.


class Bar
{
...
public:
Base(){...}
Base(const Bar& b){...} /* Copy constructor */
};

...

Bar a;
Bar b(a); // Call to copy constructor
Bar c = a; // Another call to copy constructor (implicit conversion syntax)



Also constructors/destructors are central in the RAII design pattern, which are absolutely central in C++.

[Edited by - fpsgamer on June 13, 2008 12:16:26 AM]

Share this post


Link to post
Share on other sites
Thank you for all the great replies. I understand their purpose a lot better now and I bet they will begin to make even more sense as I get further into the book :)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!