My question is, should I always use a constructor and destructor when I make my classes? I always have to initialize the variables, correct? What is a situation in which they shouldn't be used? Thanks!
My question is, should I always use a constructor and destructor when I make my classes? I always have to initialize the variables, correct? What is a situation in which they shouldn't be used? Thanks!
Well I always have a constructor (at least a default constructor) but I rarely need destructors. You only really need a destructor when a) you know whoever using your code won't be brilliant enough to call your Destroy() method or something like this or b) you want to make sure that a)'s stupid user will have done this important task (sometimes it's critical).
So a default constructor would be:
Correct?Code:class Monkey { Monkey(); };
If your class does not need to obtain or initialize any resources, and does not need to clean up after itself, you can allow the compiler to automatically generate the constructor and destructor for you.
>> a) you know whoever using your code won't be brilliant enough to call your Destroy() method or something like this
That's just not right. An object should clean up after it's own mess, you don't want to force it upon the client to do this task. And what does b) mean?
intialize all members inside constructors
Kuphryn
Base classes need to have a virtual destructor.
If you have any dynamically allocated memory in your classes then you'll have to provide a copy constructor (and assignment operator) to ensure that the pointer(s) to such memory are not simply copied but that separate memory is allocated and the contents properly copied across.
[edit]If you don't want a particular class to be copyable, you'll need to declare its copy constructor (and assignment operator) as private or protected. Similarly, you might not want to instantiate a non-abstract base class, in which case you should declare any constructors for such a class as protected.[edit]
If your class has variables that require initialisation then you should prefer an initialisation list which will require you to define your own constructor.
Other than that, I think you can pretty much please yourself.
Last edited by Ken Fitlike; 05-15-2006 at 07:35 PM. Reason: editing
CProgramming FAQ
Caution: this person may be a carrier of the misinformation virus.
As a general rule, I believe in ensuring classes are initialised so they contain valid (in the sense of complying with conditions that are relevant to the class) data.
I generally avoid writing copy constructors (and assignment operators) unless forced to. The only times I'm forced to are when the compiler supplied versions of these constructors does not behave correctly (eg classes that dynamically allocate memory or other resources).
I also attempt to avoid writing classes that have a significant number of constructors, although the meaning of "significant" depends on the class.