user3023605
user3023605

Reputation: 459

Base class functions that use derived class variables

In c++, Is there a standard way to create a function in a base class that can use the variables of derived classes?

class Foo{
private:
    int x;
public: 
    Foo(){
        x = 2;
    }
    void print(){
        std::cout << x << std::endl;
    }
};

class Derived : public Foo{
private:
    int x;
public: 
    Derived(){
        x = 4;
    }

};


void main()
{
    Derived a;
    a.print();
}

This code prints the variable of the base class ( 2 ). Is there a way to make a function used by many derived classes to use the class's private variables without passing them as parameters?

Edit: My intentions are, to avoid writing the same code for each derived class. For example, I want a get_var() in all, but this function should return the variable of that own class. I know I can make virtual and override, but I was looking for a way that I don't need to write again and again.

Upvotes: 1

Views: 3822

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

No, it is not possible for the base class to access anything in the derived class directly. The only way for a derived class to share anything with its base class is by overriding virtual member functions of the base class.

In your case, however, this is not necessary: the derived class can set variable x in the base class once you make it protected, and drop its own declaration as unnecessary:

class Foo{
protected: // Make x visible to derived classes
    int x;
public: 
    Foo(){
        x = 2;
    }
    void print(){
        std::cout << x << std::endl;
    }
};

class Derived : public Foo{
public: 
    Derived(){
        x = 4;
    }
};

Upvotes: 4

Related Questions