Search code examples
c++oopchain

Why newer versions of C++ don't allow definition of pure method inside class declaration?


Why MSVC++ 2015 and its earlier versions allowed the definition of a pure virtual method inside the class declaration but On GCC 4.9 and I guess MSVC++ 2017 don't allow that:

    #include <iostream>     

    class A{
        public:
            virtual void Foo() = 0;
    };

    class B: public A {
        public:
            virtual void Foo() = 0 { std::cout << "B::Foo()" << std::endl;
            }; // Allowed on MSVC 2015 and old versions

            //virtual void Foo() = 0; // on newer versions
    };

    //void B::Foo(){
    //  std::cout << "B::Foo()" << std::endl;
    //}     // Ok here!

    class C : public B{
        public:
            void Foo(){
                B::Foo();
                std::cout << "C::Foo()" << std::endl;
            }
    };

    int main(){

    //  A aObj; // error
    //  B bObj; // error
        C cObj; // correct
        cObj.Foo();

        std::cout << std::endl;
        std::cin.get();
        return 0;
    }

Solution

  • The standard explicitly mentions that that is not allowed (e.g. C++14, §10.4./2)

    A function declaration cannot provide both a pure-specifier and a definition — end note ] [ Example: struct C { virtual void f() = 0 { }; // ill-formed }; — end example ]