Roman Rdgz
Roman Rdgz

Reputation: 13244

C++ class member not initialized (at constructor, but does at initialize method)

I have a C++ class with two constructors (a default one and another with arguments). In order to reuse code, I avoided initializing class members at the constructor level, and I'm doing it in an Initialize method instead, which I am calling from both constructors. This way, I was hopping to minimize code lines and repeated code:

Location::Location(){
    double pos[POSITION_SIZE] = {0};
    this->Initialize(const_cast<char*>(""), const_cast<char*>(""), pos);
}


Location::Location(char *id, char *code, double pos[POSITION_SIZE]){
    this->Initialize(id, code, pos);
}


void Location::Initialize(char *id, char *code, double pos[POSITION_SIZE]){
    strcpy(this->ID, id);
    strcpy(this->code, code);

    this->position[0] = pos[0];
    this->position[1] = pos[1];
    this->position[2] = pos[2];

    this->attribute1 = 0;
    this->attribute2 = 0;
}

header:

class Location{
public:
    Location();
    Location(char *id, char *code, double pos[POSITION_SIZE]);

private:
    // This method initializes the location attributes given as parameters
    void Initialize(char *id, char *code, double pos[POSITION_SIZE]);

    // Name/identifier of the location
    char ID[ID_LENGTH];
    // FIR identifier
    char code[ID_LENGTH];
    // Location's coordinates (lat, lon, alt)
    double position[POSITION_SIZE];
    // Attribute 1
    double attribute1;
    // Attribute 2
    double attribute2;
};

I know that using initialize methods is a bad praxis when used because old school coding style or avoiding the usage of exceptions at constructor for example. But my goal here was reducing code, so unless some guru of stackoverflow says the opposite, I think it is not wrong (but I'm here to learn, so please destroy all my convictions).

The problem is that I'm getting a warning for not initializing class members within the cosntructor. The compiler doesn't like them to get initialized at the Initialize method. So, any way of making the compiler happy? Should I forget aboput Initialize method usage?

Upvotes: 1

Views: 3630

Answers (1)

Nim
Nim

Reputation: 33655

I would use constructor delegation, something like:

#include <iostream>
using namespace std;

class foo
{
public:
    foo()
    : foo(1, "2", 3.) // delegate to the other constructor with defaults...
    { }

    foo(int a, std::string b, double c)
    : _a(a), _b(b), _c(c)
    { }

private:
    int _a;
    std::string _b;
    double _c;
};

int main() {
    foo f1{};
    foo f2{1, "3", 4.};
    return 0;
}

With the caveat that you can use atleast c++11...

Upvotes: 4

Related Questions