Question

Lets look at class A that comes from external library

class A {
    public:
        void method() {
            cout << "hi";
        }
};

and my abstract class B with pure virtual method()

class B {
    public:
        virtual void method() = 0;
};

i have created class D derived by A and B

class D : public A, public B {

};

But when I create an instance of D, I get following error:

error: cannot declare variable ‘d’ to be of abstract type ‘D’

How implement class D it was not an abstract class and could call method() from class A?

Sample code: http://ideone.com/yxGWvM

Was it helpful?

Solution

You must override methodin D. You can do it like this

class D : public A, public B {
public:
    void method() override {
        A::method();
    }
};

OTHER TIPS

Define the function in D and use the implementation provided by A.

class D : public A, public B {
public:
    void method() {
        A::method();
    }
};
class B {
    public:
        virtual void method() = 0;
};

B has pure virtual function, any class (D) derived from that class (B) must override to create instance of class.

So D should be,

class D : public A, public B {

    void method() 
    {
       //implementation 
    }
//other code

};

A class derived from an abstract base class will also be abstract unless you override each pure virtual function in the derived class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top