Teague Teague - 1 month ago 8
C++ Question

Why must I re-declare a virtual function from an inherited class?

I'm working on a simple C++ program and am having a difficult time understanding a compiler error I was getting. The issue was caused by me attempting to create a derived class from a base class. I've posted my code below with the same structure but have changed the names.

BaseClass.h

#ifndef BASECLASS_H
#define BASECLASS_H

class BaseClass {

public:
BaseClass(void);

virtual int method1(void) = 0;
virtual int method2(void) = 0;
virtual float method3(void) = 0;

};

#endif // BASECLASS_H


DerivedClass.h

#ifndef DERIVEDCLASS_H
#define DERIVEDCLASS_H

#include "DerivedClass.h"

class DerivedClass: public BaseClass
{

public:
DerivedClass(void);
};

#endif // DERIVEDCLASS_H


DerivedClass.cpp

#include "DerivedClass.h"

DerivedClass::DerivedClass(void)
{
}

int DerivedClass::method1(void)
{
// TODO
}

int DerivedClass::method2(void)
{
// TODO
}

float DerivedClass::method3(void)
{
// TODO
}


When attempting to compile this, I get the following error for all the virtual methods:

no 'int DerivedClass::methodX()' member function declared in class 'DerivedClass'


As soon as I declare these methods in the 'DerivedClass.h', the errors go away since the compiler is now aware of the methods.

However, I'm confused. Why was it necessary to re-declare the pure virtual functions in DerivedClass.h? When I #include DerivedClass.h, that will automatically include BaseClass.h, thus I assume my DerivedClass.cpp should be fully aware of the methods. Am I doing something incorrect?

Answer

It doesn't work this way. You need to declare the methods you're going to define, whether they're overriding a virtual method or not.

This isn't just an unreasonable requirement of the language. Without this you would be unable to define partially virtual class, i.e., you could have BaseSubtype that has common implementation of method1() but requires classes derived from it to implement method2() and method3()

Comments