重複の可能性:
実装された純粋仮想関数
と呼ばれる関数を持つ基本クラスがありますtime()
。
私の考えは、それを継承するすべてのクラスが実装しなければならない純粋仮想関数を持つことです。
ただし、デフォルトの動作も追加したいと思います。関数を呼び出す人は誰でもtime()
「hello」を出力する必要があります。
それは可能ですか?
重複の可能性:
実装された純粋仮想関数
と呼ばれる関数を持つ基本クラスがありますtime()
。
私の考えは、それを継承するすべてのクラスが実装しなければならない純粋仮想関数を持つことです。
ただし、デフォルトの動作も追加したいと思います。関数を呼び出す人は誰でもtime()
「hello」を出力する必要があります。
それは可能ですか?
The easiest way to achieve something like this would be to have something like the following:
class base {
virtual void time_impl()=0;
public:
void time() {
//Default behaviour
std::cout << "Hello\n";
//Call overridden behaviour
time_impl();
}
};
class child : public base {
void time_impl() override {
//Functionality
}
};
This way, when any child's time
function is called, it calls the base classes time function, which does the default behaviour, and then make the virtual
call to the overridden behaviour.
As Als says in the comments, this is called the Template method pattern which you can read about here:
http://en.wikipedia.org/wiki/Template_method_pattern
Althought for C++ that is a rather confusing name (as templates are something else, and "methods" don't mean anything in C++ (rather member function
).
Someone commented about the use of override, this is a C++11 feature, if you have it USE IT, it will save many headaches in the long run:
http://en.wikipedia.org/wiki/C%2B%2B11#Explicit_overrides_and_final
And also, the _impl
function should be private, UNLESS you want the user to be to bypass the default behaviour, but I would argue that's a poor design in most use-cases.
You can provide the default behavior in your base class by making your virtual
function not pure virtual
.
However, you can't force the implementation to invoke this default behavior without posing some restrictions on child's implementation (see @111111 answer for details). You should inspect you requirements to see if this is an acceptable solution.