2

According to C++ Primer 5th Edition,

"It is worth noting that we can provide a definition for a pure virtual. However, the function body must be defined outside the class. That is, we cannot provide a function body inside the class for a function that is = 0."

However, the code below works for me in VS2015. Could anyone explain why?

struct A
{
    virtual void fn1() = 0 { cout << "A::fn1()" << endl; }
};

struct B : public A
{
    virtual void fn1() override { cout << "B::fn1()" << endl; }
};

int main()
{
    B b;
    b.fn1();    // "B::fn1()"
    b.A::fn1(); // "A::fn1()"

    cin.get(); return 0;
}
yb z
  • 21
  • 2
  • 3
    This is a compiler extension. – n. m. could be an AI Dec 16 '19 at 15:39
  • 2
    MSVC is being lenient and appears to allow this code as a non-standard extension. Other compilers will reject such code: https://godbolt.org/z/vs8Srz – Max Langhof Dec 16 '19 at 15:40
  • 1
    Compiled using `g++` and got : `test.cpp:7:24: error: pure-specifier on function-definition virtual void fn1() = 0 { cout << "A::fn1()" << endl; }` – ignacio Dec 16 '19 at 15:42
  • 1
    FYI; https://developercommunity.visualstudio.com/content/problem/187888/msvc-incorrectly-allows-pure-virtual-function-defi.html – bertubezz Dec 16 '19 at 15:56
  • Of course, being _lenient_ and allow various extensions is a form of vendor lock-in: porting the code to a different compiler implies potentially large effort. – Dietmar Kühl Dec 16 '19 at 16:48

0 Answers0