Home > Back-end >  How can change the value of a member of a base class?
How can change the value of a member of a base class?

Time:05-12

I have three classes:

class Operation{
public:
    virtual bool execute(const Solution& sol, Solution& newSol) = 0;
    pair<int, int> pair_routes;
};

class OperationR : public Operation{
public:
    OperationR(){};
    bool execute(const Solution& sol, Solution& newSol);
    pair<int, int> pair_routes;
};

class OperationD : public Operation{
public:
    OperationD(){};
    bool execute(const Solution& sol, Solution& newSol);
    pair<int, int> pair_routes;
};

The value of pair_routes changes inside the execute() function.

In the main() function, I create a vector of class Operation like this:

vector<Operation*> operations;
    
OperationR* opr = new OperationR();
operations.push_back(opr);
    
OperationD* opd = new OperationD();
operations.push_back(opd);
    
Operation* op = operations[0];
Solution s1, s2;
op->execute(s1, s2);   // line 1
    
cout << op->pair_routes.first;

There is no problem in the compilation, but even if the value of pair_routes changes in line 1, it returns the value 0. I tried to initialize this member in the base class with different values, and each time the program returns this value.

CodePudding user response:

Your derived classes are declaring their own pair_routes members that shadow (ie, hide) the pair_routes member of the base Operation class.

When you execute op->execute(), op is pointing at an OperationR object, so it is calling OperationR::execute(), which is then modifying the OperationR::pair_routes data member. But then afterwards, you are display the Operation::pair_routes data member instead, which was not modified.

Get rid of the shadowing pair_routes data members, you don't need them. The derived classes have access to the pair_routes data member of the base class.

class Operation{
public:
    virtual bool execute(const Solution& sol, Solution& newSol) = 0;
    pair<int, int> pair_routes;
};

class OperationR : public Operation{
public:
    OperationR() = default;
    bool execute(const Solution& sol, Solution& newSol) override;
    //pair<int, int> pair_routes; // <-- get rid of this
};

class OperationD : public Operation{
public:
    OperationD() = default;
    bool execute(const Solution& sol, Solution& newSol) override;
    //pair<int, int> pair_routes; // <-- get rid of this
};
  • Related