Home > Mobile >  Change base class fields in derived class with base class method
Change base class fields in derived class with base class method

Time:04-02

I am not sure where I am wrong here, but there seems to be some miss conception from my side. I have a base class and a derrived class and some methods like in this example.

class Base {
    public:
    int curr_loc;
    Base(int curr_loc):curr_loc(curr_loc)
    void reset(int curr_loc){
        curr_loc = curr_loc;
    }
}

class Derived: public Base{
    public:
    Derived(int curr_loc):Base(curr_loc)
}

Derived a(1);
a.reset(2);
a.curr_loc //is still 1?

When I call now "a.curr_loc", I still get 1. I thought that I would override the value with the method reset, but this is done on a different object... Is there a way to do this without I need to copy the functions of the base class for the derrived class?

CodePudding user response:

curr_loc = curr_loc;

This line does nothing. It assigns a variable to itself. The fact that there's also an instance variable called curr_loc is not referenced here, since there's a local variable of the same name shadowing it.

You can either rename the argument to be something else or you can explicitly use this to assign.

this->curr_loc = curr_loc;

CodePudding user response:

This code snippet

class Base {
    public:
    int curr_loc;
    Base(int curr_loc):curr_loc(curr_loc)
    void reset(int curr_loc){
        curr_loc = curr_loc;
    }
}

class Derived: public Base{
    public:
    Derived(int curr_loc):Base(curr_loc)
}

has syntactic errors.

You need to write

class Base {
    public:
    int curr_loc;
    Base(int curr_loc):curr_loc(curr_loc){}
    void reset(int curr_loc){
        Base::curr_loc = curr_loc;
    }
};

class Derived: public Base{
    public:
    Derived(int curr_loc):Base(curr_loc) {}
};

Pay attention to to the member function reset definition. It should be defined either like

    void reset(int curr_loc){
        Base::curr_loc = curr_loc;
    }

or like

    void reset(int curr_loc){
        this->curr_loc = curr_loc;
    }

Otherwise the parameter ciur_loc is assigned to itself in this statement

        curr_loc = curr_loc;

because it hides the data member with the same name of the class Base.

  • Related