Search code examples
c++abstract-classvirtualc++03

Can a base class declare a virtual method but not define it? Still defined in derived classes


#include <vector>

class M {
    public:
        M(unsigned int);
        unsigned int n;
};

M::M(unsigned int i) { n = i; }

class A {
    protected:
        char t;
    public:
        virtual ~A();
        virtual std::vector<M> foo(unsigned int);
        char getChar();
};

A::~A(){}
std::vector<M> A::foo(unsigned int u) {
    std::vector<M> v;
    return v;
}
char A::getChar() { return t; }

class B : public A {
    public:
        B();
        std::vector<M> foo(unsigned int);
};

B::B() { t = 'b'; }
std::vector<M> B::foo(unsigned int c) {
    std::vector<M> v;
    for (unsigned int i = 0; i < c; i++) {
        v.push_back(i);
    }
    return v;
}

int main() {}

In the above code, I get a warning unused parameter 'u' in A::foo(). However, removing the function entirely, I get an error that there's an undefined reference to A::foo() from B. B is implementing the virtual method and cannot find a reference to a definition in A, but why does it need to be defined in A if the expected behavior is the derived class will always override the base class, in other words, A::foo() will never ever be called?

To be more declarative, is there a way to declare a virtual method in a base class but only define it in a derived class? Consider the base method call will never happen explicitly.


Solution

  • What you are looking for is called a "pure virtual function", and you declare it in a class definition with = 0:

    class A {
        protected:
            char t;
        public:
            virtual ~A();
            virtual std::vector<M> foo(unsigned int) = 0; // <--
            char getChar();
    };
    

    You can read more about pure virtual functions and their effects at cppreference.com.