"CPP Primer" (fifth edition) says on page 541: it is worth noting that we can also provide definitions for pure virtual functions, but the function body must be defined outside the class .
but an error occurs when we do the following experiment:
-sharpinclude <iostream>
class A {
public:
virtual void printClassName() { std::cout << "This is class A" << std::endl; }
};
class B : public A {
public:
void printClassName() = 0;
};
void B::printClassName() { std::cout << "This is class B" << std::endl; }
class C : public B {
public:
void printClassName() override { std::cout << "This is class C" << std::endl; }
};
// void C::printClassName()
int main(int argc, char const *argv[])
{
A a;
B b;
C c;
a.printClassName();
b.printClassName();
c.printClassName();
return 0;
}
the error message is as follows:
a.cpp: In function "int main(int, const char**)":
a.cpp:25:7: error: cannot declare variable "b" to be of abstract type "B"
B b;
^
a.cpp:8:7: note: because the following virtual functions are pure within "B":
class B : public A {
^
a.cpp:13:6: note: "virtual void B::printClassName()"
void B::printClassName() { std::cout << "This is class B" << std::endl; }
^
that is to say, for class B which declares pure virtual functions, it is meaningless to define the function body of pure virtual functions, but this is obviously not consistent with what is said in the book. Is there any problem in this? There is still something wrong with my understanding. Thank you, boss.