Re: How to enforce a virtual fn is overloaded by derived class?
On Apr 12, 2:48 am, "Chris Morley" <chris.mor...@lineone.net> wrote:
I need to enforce requirement that the programmer overloads a particular
virtual function in all derived classes.
i.e.
class base {
public:
virtual void foo() {} // base has some handler
};
class deriv1 : public base {
void foo() {} // good overridden
};
class deriv2 : public base {
}; // bad, no overload so I want compiler to choke
You should use a pure virtual function with a definition for that
(which is, quite possibly, a feature that is unique to C++):
class base {
public:
virtual void foo() = 0; // pure virtual - must be overridden;
body cannot be defined inline, though
};
void base::foo() { // definition which can be called non-virtually
(e.g. from derived classes)
...
}
class derived : public base {
public:
virtual void foo() {
base::foo();
...
}
}
Even in this case, derived classes still do not _have_ to override foo
- but if they don't, they become abstract themselves.
class base_base abstract {
Note that "abstract" class modifier is non-standard C++ (it's a C++/
CLI extension). Furthermore, even in C++/CLI, it is not required in
this case.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]