Reputation: 18109
In this particular case, why do I have to define the non-pure virtual method in the base class in order to avoid a linker error?
This gives a linker error:
class A
{
public:
virtual ~A(){}
virtual void foo() = 0;
virtual void bar();
};
class B : public A
{
public:
void foo()
{
}
void bar()
{
}
};
int main()
{
B b;
}
Output:
/tmp/cc5E8Tit.o: In function `A::~A()':
:(.text._ZN1AD2Ev[_ZN1AD5Ev]+0x13): undefined reference to `vtable for
A' /tmp/cc5E8Tit.o:(.rodata._ZTI1B[_ZTI1B]+0x10): undefined reference
to `typeinfo for A' collect2: error: ld returned 1 exit status
But if i define the bar method in class A
it links ok:
class A
{
public:
virtual ~A(){}
virtual void foo() = 0;
virtual void bar(){}
};
class B : public A
{
public:
void foo()
{
}
void bar()
{
}
};
int main()
{
B b;
}
... no linker error.
Why is this?
Upvotes: 0
Views: 780
Reputation: 8785
R Sahu already provided standard quote related to this, I will provide slightly longer explanation why error happens — sometimes you can get away with not defining functions if they are not used, but not in this case.
Virtual functions are always used. Their address is used in virtual tables which are built for each class with virtual functions and which are used for dynamic dispatch.
Linker emits an error, because base class A
constructor sets up pointer to base class virtual table, virtual table contains pointer to bar
and linker cannot find definition of bar
member function to find its address.
Upvotes: 5
Reputation: 206607
From the C++11 Standard:
10.3 Virtual functions
11 A virtual function declared in a class shall be defined, or declared pure (10.4) in that class, or both; but no diagnostic is required (3.2).
It's OK to define a pure virtual function but it is not necessary.
It is necessary to define a virtual function if it is declared but not declared as pure virtual.
It's good that the linker complains even though the language does not require it to.
Upvotes: 4
Reputation: 5201
The answer is in the definition itself. A function is pure virtual if it is not defined. Then, if you don't flag it as pure virtual, you have to define it. It's a constraint of the C++
language.
Upvotes: 1