I've got a constructor that sets some floats (x,y,z) and then I have a function called setXYZ. Now the constructor and the function do exactly the same thing.

What's the best thing to do in this situation? Should I put the code in the function then call this from the constructor? Or is there a more efficient way?


Many Thanks,
:)

Assume a class declared like this (I have reduce it to 1 float for berevity)

class MyClass
{
public:
    MyClass(float initx);
    setX(float newx);

private:
    float x;
}

You are say since the constructor is implemented as

MyClass::MyClass(float initx)
{
    x = initx;
}

you could just call setX which does the same thing. The mistake is that you are assign in the constructor when it is more preferable to use initialiser lists so you constructor should really be

MyClass::MyClass(float initx)
: x(initx)
{
}

Nothing like setX!

A float is a simple case but get into the habit of using intiialiser lists. You will often want to use them if you have a class hierarchy anyway to initialise base classes in a specific way.

if the constructor calls some code that is also called by a class method then probably the best thing to do is to put the code into a private method that both the constructor and public member call. That is separate the implementation from the interface. Also also allows for such things as differing checks on data validity before calling the common code.

Edited 3 Years Ago by Reverend Jim: Fixed formatting

OK I think I understand that. But the purpose of me having the setXYZ function was so that I could change the XYZ after the object was created.. do I use this initialisation list on the other function too?

No intialisation lists only work on constructors which are special functions for initialising the object and they specifically initialse member variables and sub-classes rather than assigning to them.

Initialisation only happens when the object is being created so you can initialise in a member function because the object is not being created it already exists you have to assign to it.

Ah ok I see. So in my situation I would use the initialisation list in the constructor and then in the function just assign values? (like I have already done?)

Thanks :)

This article has been dead for over six months. Start a new discussion instead.