Search code examples
c++inheritancevirtual

about inheritance in C++, can a derived class get implemetation from base class without explicitly defining it


The following has the error

error LNK2001: unresolved external symbol "public: virtual void __thiscall C::Foo(void)" (?Foo@C@@UAEXXZ)

so basically C::Test() cannot inherit implementation of B::Test() automatically and we have to explicitly write it everytime in C++?

class A
{

public:  
    virtual void Foo()=0;
    virtual void Test()=0;

};

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

};

void B::Foo()
{

}



class C: public B
{
public:
    void Foo();
    void Test();
};



void C::Test()
{
}

Solution

  • If your derived class declares a virtual method from a parent class, as C does with void Foo(), then it must implement it too. If you want to inherit B's implementation, then don't declare void Foo() in C.

    class C: public B
    {
    public:
        void Test();
    };