Archived

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

Prod

Are Class Constructors really needed?

Recommended Posts

I was wondering why do we need constructors and destructors? In all my classes i have made i have had no problems with not having a constructor or destructor. What are they used for exactly? thanks.

Share this post


Link to post
Share on other sites
Wait till you have complex classes which cannot be used without having at least base assumptions on data validation. If your class contains data, it should be initialized to a default value if not explicitly specified. That''s what constructors are for.

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ | MS RTFM [MSDN] | SGI STL Docs | Google! ]
Thanks to Kylotan for the idea!

Share this post


Link to post
Share on other sites
constructors have many uses.

one common uses of constructors is to initialize objects.

in C++, all objects and variables have implicit constructors and destructors.

  
int i(10); // initializes i to 10

int* pi = new int(10); //creates a new int and initialize to 10



its possible to make explicit contructors for your udts.
explicit constructors and destructors allow implicit object management. this means that you dont call the functions yourself, they are managed by the compiler. otherwise, you would need to write your own init and deinit functions.

constructors allow initializer lists.

  
class A{
B _b;
int _length;
public:
A(): _length(10), _b(10, NULL){}
A(int length): _length(length), _b(length, NULL) {}
};


while constructors are useful for initializing data, constructors and destructors are most useful for managing dynamic data. if you create data dynamically, then you can make sure its released in the destructor. inversely, you can make sure its alloted in the constructor, or you can initialize pointers to NULL.


  
class A{
DATA* _data;
public:
A() //default constructor

{ _data = new DATA[10];}
A(int length) //overloaded constructor

{ _data = new DATA[length];}
~A()//destructor

{ SafeDeleteArray(_data);}
};


you can pass an object using a constructor.

  
void myFunc( A a);
myFunc( A(10, pi, x) );

in this example, we have a temp variable that is created and passed to the function, and then destroyed after the call.

neato huh!

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
A simple example is: imagine making a even number class which can only be used to represent even numbers. Using a constructor is the only way you can guarentee that it is created with the correct type of information (i.e. not an odd number).

The idea is that you create objects that validate the data they contain (i.e. check it is correct) and then you can safely use them from then on knowing they are correct. If, for example, you just used C style structures, there is no good way you can stop parts of your program filling them up with invalid information.

Share this post


Link to post
Share on other sites