Reputation: 11161
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
Upvotes: 1
Views: 237
Reputation: 22981
Define the function in D
and use the implementation provided by A
.
class D : public A, public B {
public:
void method() {
A::method();
}
};
Upvotes: 2
Reputation: 1362
A class derived from an abstract base class will also be abstract unless you override each pure virtual function in the derived class.
Upvotes: 1
Reputation: 18905
You must override method
in D
. You can do it like this
class D : public A, public B {
public:
void method() override {
A::method();
}
};
Upvotes: 2
Reputation: 9841
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
};
Upvotes: 1