Archived

This topic is now archived and is closed to further replies.

C++ Classes: Constructor-Destructor Help

This topic is 5094 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 just learning C++ and in the past 4 months I''ve gotten through basic Input/Ouput, Functions, Arrays, Pointers, and Strings. I get to classes and I understand how they work and what they are supposed to do but I''m having trouble understanding the Constructors and the Destrunctors. Can someone give me an explaination on how they work and maybe even some examples of how I would use them??

Share this post


Link to post
Share on other sites
Simple explanation:

Constructors and Destructors do as their name says, `construct` and `destruct` objects. In programming, constructors are generally used to initialize an object with default values and destructors are used to clean up memory that the class may have allocated. For example, this Rectangle class:


class Rectangle
{
public:
Rectangle(); // default constructor

Rectangle(int x, int y, int width, int height); // another constructor

~Rectangle(); // destructor


private:
int x;
int y;
int width;
int height;
};

Rectangle::Rectangle() :
x(0),
y(0),
width(0),
height(0),
{
}

Rectangle::Rectangle(int x, int y, int width, int height) :
x(x),
y(y),
width(width),
height(height),
{
}

Rectangle::~Rectangle()
{
// this class don''t need to do anything here,

// but it may want to do something like:

//

// delete myPointer;

}


Now, how do we use these constructors?


Rectangle r1; // default constructor called

Rectangle r2(); // default constructor called

Rectangle r3(5, 5, 16, 16); // non-default constructor called



Constructors and Destructors basically make life easier for us! Hope this helps some.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
A constructor is called when the class object is created, you can use it to set the values of your variables or allocate memory for pointers or whatever. And one use for the destructor(called when your object is destroyed) is to free up your pointers.

Here''s an example:


class poop
{
public:
poop();
~poop();
private:
short n;
short* p;
};

poop::poop()
{
n = 5; //set a value for n

p = new unsigned short; //allocate memory for p

}

poop::~poop()
{
delete p; //release memory for p

p=NULL;
}


Didn''t test that but it shouldn''t have any compiler errors I hope

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
sorry it should be

poop:oop()
{
n = 5; //set a value for n
p = new short; //allocate memory for p
}

I guess I was wrong

Share this post


Link to post
Share on other sites