Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Getters-Setters in Implementation File

I'm relatively new to C++ and I think that my question may be understood best by example. In my header file, suppose I have

class myClass{
    public:
        double getVar1();
        void setVar1(double newVar1);
        void copyVar1(myClass* dat);

    private:
        double var1;
};

In my implementation .cc file, when implementing the copyVar1 method, should I do

void myClass::copyVar1(myClass* dat){
   var1 = dat->var1;
}

or

void myClass::copyVar1(myClass* dat){
   var1 = dat->getVar1();
}

where in the second case, I use the getter method instead. Both work properly in Visual C++, but I would like to know which is better to use in practice.

Thank You for your comments!

like image 721
A-A Avatar asked Aug 04 '11 14:08

A-A


1 Answers

Best practices? Overload the assignment operator instead of writing a method.

myClass & myClass::operator=(const myClass & dat)
{
   var1 = dat.var1; // or dat.getVar1()
   return *this;
}

As for using the field or calling a setter... it's all a matter of personal taste. If your getter has some side effect, then you probably should call it, otherwise, use the field.

So, a big "depends".

like image 194
Etienne de Martel Avatar answered Sep 28 '22 16:09

Etienne de Martel