Search code examples
c++inheritanceconstructorvariable-assignmentbase-class

Change base class fields in derived class with base class method


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 derived 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 derived class?


Solution

  • 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.