Search code examples
c++visual-c++virtualdefinition

Why do I have to specify pure virtual functions in the declaration of a derived class in Visual C++?


Given the base class A and the derived class B:

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

class B : public A {
public:
  void g();
};

void B::g() {
    cout << "Yay!";
}

void B::f() {
    cout << "Argh!";
}

I get errors saying that f() is not declared in B while trying do define void B::f(). Do I have to declare f() explicitly in B? I think that if the interface changes I shouldn't have to correct the declarations in every single class deriving from it. Is there no way for B to get all the virtual functions' declarations from A automatically?

EDIT: I found an article that says the inheritance of pure virtual functions is dependent on the compiler: http://www.objectmentor.com/resources/articles/abcpvf.pdf

I'm using VC++2008, wonder if there's an option for this.


Solution

  • Yes, in C++ you have to explicitly clarify your intention to override the behavior of a base class method by declaring (and defining) it in the derived class. If you try to provide a new implementation in derived class without declaring it in class definition it will be a compiler error.