Particle Swarm Optimization algorithm This is part of a Particle Swarm Optimization algorithm, a snippet of a Particle class implementation.

/**
 * Particle class constructor
 * @param p - the position of the particle
 * @param v - the velocity of the particle
 */
Particle::Particle(std::array&lt;double, 30&gt; p, std::array&lt;double, 30&gt; v) {
    bestFitness = fitness = rastriginEvaluation(p);
    bestPosition = position = p;
    velocity = v;
}

// setter methods
void Particle::setFitness(double f) { fitness = f; }
void Particle::setBestFitness(double f) { bestFitness = f; }
void Particle::setPosition(std::array&lt;double, 30&gt; p) { position = p; }
void Particle::setBestPosition(std::array&lt;double, 30&gt; p) { bestPosition = p; }
void Particle::setVelocity(std::array&lt;double, 30&gt; v) { velocity = v; }


Notice the constructor directly accesses member attributes yet I have setter methods. Should I be using the setter methods to initialize attributes? Either is fine, I wonder what is more proper.

For example, instead of:

bestFitness = fitness = rastriginEvaluation(p);
bestPosition = position = p;
velocity = v;


I could do:

setFitness(rastriginEvaluation(p));
setBestFitness(rastriginEvaluation(p));
setPosition(p);
setBestPosition(p);
setVelocity(v);


For this example, rastriginEvaluation() is called twice, when the original code only calls it once. It is therefore slower but what is better practice?

I could also wonder about getter methods in the mix:

setFitness(rastriginEvaluation(p));
setBestFitness(getFitness());
setPosition(p);
setBestPosition(getPosition();
setVelocity(v);


If it makes a difference, all attributes are private.
As a general rule, if the only thing your getters and setters do is contain a single statement, a return or assignment respectively, there is no need to make the variable private and it should be declared public.

Specifically to your question: Neither of your approaches are considered "best" nor "proper" practice. You should be using an initializer list before the constructor's body:

Note: There is no indication of what order the variables were declared in the class declaration. I've made a guess here, but they are initialized in the order they are declared regardless of what order you put them in the list so if I've got it backwards and fitness is declared first things will silently break at run-time.

Particle::Particle(std::array&lt;double, 30&gt; p, std::array&lt;double, 30&gt; v)
: bestPosition(p)
, position(p)
, velocity(v)
, bestFitness(rastriginEvaluation(p))
, fitness(bestFitness)
{
    /* DO NOTHING */
}