C++ Class – Purpose of Creating a Member Function with the Same Type

cclassobject

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 and Class2 should be something like:

class Class1 {
public:
  int i;
  Class1(int parameter) : i(parameter) {}  // This is a constructor
};

class Class2 {
public:
  int i;
  void function(int parameter) {i = parameter;} // This is a init function
};

and

Class1 object1(10);
Class2 object2;
object2.function(10);

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 use i 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:

    const Class1 object1(10);
    

    you cannot write:

    const Class2 object;   // error (uninitialized const object)
    object2.function(10);  // error (attempt to change the const object)
    
  • constructor is always more or equally efficient as having code outside

  • many other reasons (see references).

Technicalities

  • it's possible to re-initialize an object of a class using its constructor via placement new. Of course it's ugly beyond description.
  • there are reasons to prefer init functions. Init functions are able to call virtual functions on the object. This doesn't always work in a constructor, because in the constructor of the base class, the derived class part of the object "doesn't exist yet", and in particular you can't access virtual functions defined in the derived class. Instead, the base class version of the function is called, if defined (see also Why use an initialization method instead of a constructor?).

References

Related Topic