An example, then.
This is a class named foo.
foo is a class blueprint. To use it, we must first create the object mentioned in the blueprint. In C++, we call it creating an instance (of the object mentioned in the blueprint).
You can compare this to the class blueprint being a car blueprint. We can't use the blueprint to drive, now can we? First, we must build a car from the blueprint. This is called creating an instance.
Now, when we create an instance of a class, it must first be constructed from its blueprint. This is the work of the constructor (in other words, the constructor makes an object from a blueprint).
You can compare the constructor as a factory. The factory takes a order for your blueprint and builds a car for you.
If our above example, foo is actually empty. It has no constructor. In this case, the compiler is kind enough to add a "default" constructor. It just makes an object from the blueprint and nothing more.
We can create more constructors, that do special things.
You can compare this to a special factory that builds a car and maybe colors it or things like that.
However, when we add a specialized constructor, the compiler is not kind enough to add its "default" constructor for us! We need to add it ourselves for it to work.
Constructors often take different amount of information (like what color do you want your car to be?). To pass along this information when creating an instance, we use the syntax:
Code:
class car
{
car(std::string color) {}
};
int main()
{
car my_car2; // Error
car my_car("red"); // OK
}
(In this example, we create a car whose color should be red, which is what we tell the constructor.)
Note again that when we do this, the default constructor is no longer there.
A default constructor looks like:
Code:
class car
{
car() {}
};
int main()
{
car my_car; // OK
car my_car("red"); // Error
}
Because it takes no arguments, we can create an instance of it like this:
Code:
int main()
{
car my_car;
}
If we want both a default constructor and a specialized constructor, we must add the default constructor ourselves:
Code:
class car
{
car() {}
car(std::string color) {}
};
int main()
{
car my_car("red"); // OK
car my_car2; // OK
}