Can the pure virtual function of the current class of CPP: be defined outside the class?

"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.

CPP
Mar.23,2021

first of all, a class that has a pure virtual function is an abstract class and cannot instantiate an object, so an error will be reported in B b. This is why
1 and 3 reported errors.
if the second error is reported, I think it is possible that abstract classes cannot be inherited, but can be inherited


classes with pure virtual functions are abstract classes and cannot be instantiated;
pure virtual functions can have function bodies, which is indeed meaningless for use, but can provide implementation reference for subclasses to implement this pure virtual function.

Menu