tobilocker
tobilocker

Reputation: 981

Access another Base Classes member from Abstract Base Class

I wonder if it is possible to declare a pure virtual function in class AbstractBase and make a Base classes member visible in Derived so it will use the member of Base and not look for a implementation in Derived. So far, i tried making Base's member visual by trying to use using but it won't compile since the look up, in this case, seems to ignore using. Is this possible at all? Here is my code:

#include <iostream>

using namespace std;

class AbstractBase {

public:
    AbstractBase(){}
    virtual ~AbstractBase(){}

protected:
    virtual void f() = 0;


};

class Base {

public:
    Base(){}

protected:
    void f() {cout << "called Base's f()" << endl;}

};

class Derived : public Base, public AbstractBase {

public:
    Derived(){}
    //using Base::f; /*this won't compile*/
private:
    void f(){} /*Access Base's f() here rather than implement*/


};

int main()
{
    Derived d;
}

Upvotes: 1

Views: 50

Answers (2)

AMA
AMA

Reputation: 4214

It looks to me that you would like f() to be pure-virtual but provide default implementation. In this case, it can be achieved this way:

#include <iostream>

using namespace std;

struct AbstractBaseWithDefaultF 
{
    virtual ~AbstractBaseWithDefaultF() = default;
    virtual void f() = 0;
};
void AbstractBaseWithDefaultF::f()
{
    cout << "called AbstractBaseWithDefaultF's f()" << endl;
}

struct Derived : AbstractBaseWithDefaultF
{
    void f() override 
    {
        AbstractBaseWithDefaultF::f();
        cout << "called Derived's f()" << endl;
    } 
};

int main()
{
    Derived d;
    d.f();
}

Output:

called AbstractBaseWithDefaultF's f()
called Derived's f()

Here's a live Wandbox example.

Upvotes: 1

pSoLT
pSoLT

Reputation: 1052

Use :: operator:

class Derived : public Base {

public:
    Derived(){}
private:
    void f(){ Base::f() }  
};

Also, you don't need to inherit from AbstractBase.

Upvotes: 2

Related Questions