Question

I've to build a timespan class with a rather complex setting process. There will be several constructors. Is it a bad idea to call a setter in the constructors?

I know I shouldn't call non-private setters directly to avoid problems if the setter gets overwritten in a derived class. I thought of either creating the real setter private and wrap a public setter around and call the private setter in the constructor to avoid having to declare it final.

class A {
    public:
         A(sometype data1, sometype data2);

         void setData1(sometype data1);
         void setData2(sometype data2);

    private:
         void p_setData1(sometype data1);
         void p_setData2(sometype data2);
};

A::A(sometype data1, sometype data2) {
    p_setData1(data1);
    p_setData2(data2);
}

void A::setData1(sometype data1) { p_setData1(data1); }
void A::setData2(sometype data2) { p_setData2(data2); }

void A::p_setData1(sometype data1) {
     //Complex validation and calculations
}

void A::p_setData2(sometype data2) {
     //Complex validation and calculations
}

Does anyone have best practices?

Was it helpful?

Solution

Regarding

“I know I shouldn't call non-private setters directly to avoid problems if the setter gets overwritten in a derived class.”

This is largely not a problem. Even with virtual setters, the definitions used when constructing a class A are the ones for dynamic type A. C++ is safe that way, as opposed to Java and C# (where you risk that a virtual call ends up in derived class code before the base class invariant has been established, and bang).

Regarding best practice, it is to be critical of setters and getters. They do have a purpose in a language with introspection, where e.g. "designer" tools can use them, but not so much in C++. So, best practice is to always ask, do I really need them, can I design some other way (e.g. move instead of setxy (which may not sound very different, but consider a call from a constructor – move doesn't make so much sense during construction)).

OTHER TIPS

Is it a bad idea to call a setter in the constructors?

No - using setters inside your constructors allows you to reuse the setter logic without defining it in both the setter method and the constructor. This means that you would only need to make changes in one place instead of in both the setter and the constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top