Under what circumstances is it advantageous to give an implementation of a pure virtual function?

前端 未结 6 544
礼貌的吻别
礼貌的吻别 2020-12-05 13:37

In C++, it is legal to give an implementation of a pure virtual function:

class C
{
public:
  virtual int f() = 0;
};

int C::f() 
{
  return 0;
}

6条回答
  •  盖世英雄少女心
    2020-12-05 14:24

    G'day,

    Concerning providing a default implementation for a member function declared in a base class, the only reason I can think of at the moment is where you want to provide a default implementation of the behaviour as a possible implementation choice for someone who is specialising the base class.

    The author of the derived class can chose to use the default implementation provided by the base class author instead of adding their own specialised implementation.

    This is generally the case where people object to having separate functions to provide an interface and a default implementation of the behaviour yet they still want separation between default implementation and the associated interface.

    Ah, just saw @Martin York's post which provides an example.

    Actually, Scott Meyers discusses this in his book "Effective C++". It's Item 36 in the 1st edition.

    HTH

    cheers,

提交回复
热议问题