Search code examples
c++virtualsettergetter

C++ - Getting and setting member variable within same method?


I have a class that derives from a base class that contains its own member variable. In order to keep everything in the classes encapsulated, I'm trying to figure out a clean approach to setting this member variable at the same time retrieving it in the same method. Here is what the method looks like (this is pseudo code and probably won't compile):

class Base
{
    virtual void MyVirtualMethod(double &output1, Object &output2)
    {
        // do base class stuff (does not set output1 because it does not need to)...
        output2 = whatever;
    }
}

class Derived
{
public:
    virtual void MyVirtualMethod(double &output1, Object &output2)
    {
        // do derived class stuff...

        m_DerivedMember = whatever;

        // do more stuff...

        output1 = m_DerivedMember;
        output2 = whatever2;
    }

private:
    double m_DerivedMember;
}

Calling code #1

std::vector<DataPack> dataPack;

for each Base pointer...
{
    double output1(100); // some default value
    Object output2;
    base->MyVirtualMethod(output1, output2);

    dataPack.push_back(DataPack(output1, output2));
}

Calling code #2

double output1(100); // some default value
Object output2;
base->MyVirtualMethod(output1, output2);

// do more stuff but does not actually use output1, just output2...

While this works, it just doesn't seem clean to me. I guess the bigger question I'm asking myself is whether it's a good idea to use the same method as a getter and a setter at the same time? Thanks!


Solution

  • To answer your question, separate getters and setters are at the core of encapsulation. While it may save you an extra function call, it's much cleaner and safer to have separate functions for getting and setting. Here's some tweaked code to understand better

    class Derived : public Base
    {
    public:
        virtual void MyVirtualMethod(double &output1, Object &output2)
        {
            // do derived class stuff...
    
            m_DerivedMember = whatever;
    
            // do more stuff...
    
            output1 = m_DerivedMember;
            output2 = whatever2;
        }
    
    
    /*
    The setter
    */
    void setDerivedMember(double m){
        m_DerivedMember = m;
    }
    
    
    
    
    /* 
    the getter
    */
    
    double getDerivedMember(){
    
        return m_DerivedMember;
    }
    
    
    private:
        double m_DerivedMember;
    }
    

    And we could invoke these functions like:

    Derived d(1.5, string("I'm a string"));
    d.setDerivedMember(5.00);
    cout <<"Derived Member Value: " d.getDerivedMember()<<endl;
    

    It would output:

    Derived Member Value: 5.00
    

    Hope that makes sense!