4tehlolxz
4tehlolxz

Reputation: 117

Return value from Derived class to Base class

I have a value in the derived class that I want to return using a function from the base class, is that possible? Or do I have to have the variable declared in the base class to do so?

Would I just call the function in the derived class?

class Base
{
    public:
        int getNum() const { return number; }
};

class Derived : public Base
{
    private:
        int n = 50;
};

Upvotes: 4

Views: 1375

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

I have a value in the derived class that I want to return using a function from the base class, is that possible?

Yes, you can use a reference passed to the base classes constructor like so:

class Base
{
    public:
        Base(int& number_) : number(number_) {} 
        int getNum() const { return number; }
    private:
        int& number;
};

class Derived : public Base
{
    public:
        Derived() : Base(n) {}
    private:
        int n = 50;
};

Another way to do it (without using virtual getNum() const;) is using a templated base class (aka static polymorphism):

template <typename D>
class Base
{
    public:
        int getNum() const { return static_cast<D*>(this)->getNum(); }
};

class Derived : public Base<Derived>
{
    public:
        Derived() {}
        int getNum() const { return n; }
    private:
        int n = 50;
};

Upvotes: 4

Adi Levin
Adi Levin

Reputation: 5233

The way to do it is through virtual functions. The base class doesn't have direct access to the derived class members, but it has access to methods defined on the derived class, if they are virtual methods defined as follows:

class Base
{
public:
    virtual int getNum() const = 0;
};

class Derived : public Base
{
public:
    virtual int getNum() const {
        return n;
    }
private:
    int n = 50;
};

Here is a usage example:

int main() {
    Base* b = new Derived;
    std::cout << b->getNum();
    delete b;
}

Upvotes: 2

Related Questions