Every class doesn't need to have a constructor/destructor, but every class will have one in the end. If you do not provide one, the compiler will create one. A constructor is the very first thing that happens when an object is created, while the destructor is called when a object is deleted or goes out of scope.
Consider
Code:
---------------------- Car.h----------------------
class Car
{
public:
Car();
virtual ~Car();
void Drive();
protected:
private:
int numberOfWheels;
Engine *engine;
};
---------------------- Car.cpp----------------------
#include "Car.h"
Car::Car() :
numberOfWheels(4)
{
this->engine = new Engine(4); // Create a 4 cyl engine for this car
}
Car::~Car()
{
delete engine;
}
void Car::Drive()
{
engine->start();
// Do stuff
engine->stop();
}
---------------------- Main.cpp----------------------
#include "Car.h"
int main(int argc, char** argv)
{
Car *myCar = new Car(); // <-- Constructor called
myCar->Drive();
delete myCar; // <-- Destructor called
{ // Beginning local scope
Car differentCar; // <-- Constructor called
differentCar.Drive();
} // Scope ends, differentCar destructor called
}
As you can see, when car is "new"'d, the constructor is called. The constructor then sets up some default variables and in this case, allocates some memory to represent the engine ( a class not included ). Then delete is called, which results in the constructor getting called to clean things up. If there wasn't a destructor, the memory allocated for engine would never have been released, resulting in a memory leak.
Then back to main.cpp, you will notice another Car being created, although not using new. This still results in the constructor being called. Then when the variable differentCar goes out of scope, the destructor is called and its memory is cleaned up and the object is disposed.
You can actually have multiple constructors, that take a variety of parameters. For example, I could have added: Car::Car(int numCylinders) and Car::Car(string carName), etc. Constructors however cannot return a value, so you should keep internals to a minimum. There is however only ever a single destructor.
Originally Posted by
cplusplusnoob
Hey everyone, sorry for bringing up this question, knowing that there are thousands of online tutorials and books, but I have gone through mostly every kind of tutorial I can find, and I still need some better explaining on when too set up a 'class' and how..?
I'm quite new too C++ but knowledgable on the basics, and I'm very interested in 'classes'. I know that a class HAS to have a constructor and a destructor ( I know a constructor initialize's variables, but I don't understand what they mean about the destructor being used to clean up the constructor's mess?) I know about "public", "private", and "protected", but besides that I just can't understand what i'm doing..?