Reputation: 930
I am trying to learn inheritance in c++. I wrote some code to learn virtual functions.
#include <iostream>
using namespace std;
class A {
int a;
public:
A() {}
virtual int get_count() const = 0;
int get_A() { return a; }
};
class B : public A{
public:
int b;
B() {}
B(A& base)
: b(base.get_count()) {}
virtual int get_count() const { return 10; }
};
void func(A& base) {
B derived(base);
cout << derived.b;
}
int main() {
A base;
B derived;
func(derived);
}
When I try to compile I get this error:
test_inheritance_vir.cpp: In function ‘int main()’:
test_inheritance_vir.cpp:32: error: cannot declare variable ‘base’ to be of abstract type ‘A’
test_inheritance_vir.cpp:5: note: because the following virtual functions are pure within ‘A’:
test_inheritance_vir.cpp:10: note: virtual int A::get_count() const
Can you please tell me what I am doing wrong?
Upvotes: 1
Views: 138
Reputation: 5674
The answers above are the technical reasons why it won't work, but there's a more insidious problem in that the design doesn't make sense. You're creating a B to add some functionality to your A. If you also create a C that extends A, do you really want to turn that into a B?
The classic example of inheritance is animals. Zebra and Giraffe are both Animals, so a class hierarchy would look like this
class Animal
{
stuff
}
class Zebra : public Animal
{
more stuff
}
class Giraffe : public Animal
{
different stuff
}
It doesn't make much sense to turn a Zebra into a Giraffe, though, even though both are animals.
Upvotes: 0
Reputation: 15870
The way you have implemented A
(below) causes it to be an abstract base class.
class A
{
int a;
public:
A() {}
virtual int get_count() const = 0; // this is a pure virtual function
int get_A() { return a; }
};
It can only be used as a pointer to a derived class that implements the pure virtual functions:
int main()
{
B derived;
A* pA = new B; // this is okay
delete pA;
return 0;
}
Upvotes: 1
Reputation: 4012
The method virtual int get_count() const = 0;
is pure virtual. You can't create an object of a class that is abstract (or in other words - has a pure virtual member). If you want to create an object of A, remove the = 0
and define the function (with an empty body if you need):
virtual int get_count() const{};
should work.
Upvotes: 1
Reputation: 5101
You are trying to instantiate an object of type A with A base;
. It's not possible as A contains a pure virtual function. (get_count()
) Suppose I tried calling base.get_count()
.
Upvotes: 4