开发者

C++'s pure virtual function implementation and header files

I'm having some trouble implementing pure virtual functions inherited from some abstract class, when the classes in question are divided into *.h and *.cpp files. The compiler (g++) tells me that the derived class cannot be instantiated because of the existence of pure functions.

/** interface.h**/
namespace ns
{
    class Interface {
        public:
            virtual void method()=0;
    }
}

/** interface.cpp**/
namespace ns
{
    //Interface::method()() //not implemented here
}

/** derived.h **/
namespace ns
{
    class Derived : public Interface {
        //note - see below
    }
}

/** derived.cpp **/
namespace ns
{
    void Derived::Interface::method() { /*doSomething*/ }
}

/** main.cpp **/
using namespace ns;
int main()
{
    Interface* instance = new Derived; //compiler error
}

Does this mean that I have to declare the method() twice - in the Interface's *.h and in th开发者_如何学编程e derived.h too? Is there no other way around?


You have to declare your method in the subclass.

// interface.hpp
class Interface {
public:
    virtual void method()=0;
}

// derived.hpp
class Derived : public Interface {
public:
    void method();
}

// derived.cpp
void
Derived::method()
{
    // do something
}


You forgot to declare Derived::method().

You tried to define it at least, but wrote Derived::Interface::method() rather than Derived::method(), but you did not even attempt to declare it. Therefore it doesn't exist.

Therefore, Derived has no method(), therefore the pure virtual function method() from Interface was not overridden... and therefore, Derived is also pure virtual and cannot be instantiated.

Also, public void method()=0; is not valid C++; it looks more like Java. Pure virtual member functions have to actually be virtual, but you did not write virtual. And access specifiers are followed by a colon:

public:
    virtual void method() = 0;


You also did not call constructor properly - it's also a method;

 Interface* instance = new Derived;

Should be

 Interface* instance = new Derived();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜