Quentin Geissmann
Quentin Geissmann

Reputation: 2240

Using parent class constructor to reassign value to inherited variables

I have a C++ class B inherited from a class A. I probably miss an important concept of OOP and this certainly quite trivial, but I do not understand how I can, after the instantiation of B, use the constructor of A inside B to reassign new values only to the local variables inherited from A:

Class A

class A{
    public:
        A(int a, int b){
            m_foo = a;
            m_bar = b;
            }
    protected:
        int m_foo;
        int m_bar;
};

Class B

class B : public A{
    public:
        B(int a, int b, int c):A(a,b),m_loc(c){};
        void resetParent(){
            /* Can I use the constructor of A to change m_foo and 
             * m_bar without explicitly reassigning value? */

            A(10,30); // Obviously, this does not work :)

            std::cout<<m_foo<<"; "<<m_bar<<std::endl; 
            }
    private:
        int m_loc;
};

Main

int main(){
    B b(0,1,3);
    b.resetParent();
    return 1;
    }

In this specific example, I would like to call b.resetParent() which should call A::A() to change the values of m_foo and m_bar (in b) to 10 and 30, respectively. I should therefore print "10; 30" rather than "0; 1".

Thank you very much for your help,

Upvotes: 0

Views: 1536

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596101

No, you cannot call the base class constructor to reset the values. However, the values you want to reset are declared as protected which means B has direct access to them:

void resetParent()
{
    m_foo = 10;
    m_bar = 30;

    std::cout << m_foo << "; " << m_bar << std::endl; 
}

If A has an = assignment operator defined, you could alternatively declare a temp A instance and assign it to the base class:

void resetParent()
{
    *this = A(10, 30);
    // or:
    // A::operator=(A(10, 30));

    std::cout << m_foo << "; " << m_bar << std::endl; 
}

Upvotes: 2

alexrider
alexrider

Reputation: 4463

You can't use constructor to change an object, only to construct it. To change an already constructed object you need to use it's public and protected (in case of a derived class) members. In your example A needs to implement a reset() member function that can be later used to reset it's state.

Upvotes: 3

Related Questions