I'm sure I'll botch some of the specific terminology, but what is the difference between object
and object2
in this implementation? Is the only purpose of the first method (prototyping the class's function by the same name of the class) just to save typing? At the end of the code, does object==object2
?
//first method
class Class1{
public:
int i;
Class1 (parameter);
};
Class1::Class1 (parameter){
i = 10;
}
Class1 object1(parameter);
//second method
class Class2{
public:
int i;
void function (parameter);
};
Class2::function (parameter){
i = 10;
}
Class2 object2;
object2.function(parameter);
(C++11)
Best Answer
Class1
andClass2
should be something like:and
The value of
i
will be the same:object1.i == object2.i
but the purpose of the constructor is NOT to save typing.as Joel said in a comment , with the constructor it's mandatory to assign a value to
i
, while with the init function you could usei
without a previous explicit assignment.In properly designed OO-code the constructor is responsible for establishing the class invariants (here
i
should be a private data member). Without a constructor each use of the class must first ensure that the object has been properly built.You cannot re-initialize an object of a class using its constructor (*) but you can use
operator=
.const
objects can be created only via constructor:you cannot write:
constructor is always more or equally efficient as having code outside
many other reasons (see references).
Technicalities
References