开发者

Should unimplemented base class functions be 0'd?

which of the following 开发者_如何学Pythonis better practice?

class Foo {
virtual void unimplementedFunc() = 0;
};

Or

     class Foo {
        virtual void unimplementedFunc();
        };

//in cpp
void Foo::unimplementedFunc()
{
   //not implemented in base
}

Thanks


It depends on your requirements. Are derived classes required to implement the method themselves or is it optional? Does it make sense to allow instantiating the base class directly?

If an implementation is required, then let the compiler enforce it by making it a pure virtual method.


class Foo {
virtual void unimplementedFunc() = 0;
};

You have a pure virtual function inside Foo, so Foo is an abstract class. In other words you cannot instantiate Foo. Most derived classes are required to provide the implementation of the virtual function.

On the other hand the second version declares a virtual function (not pure) and defines it outside the class. Derived classes can override the function to achieve the desired behaviour.

Note : A pure virtual function may optionally have a body. For example

class Foo {
    virtual void unimplementedFunc() = 0;
    };

void Foo::unimplementedFunc() {} //is valid


There is a difference between the two apart from it being unimplemented. By setting it to zero, you've made the first Foo class an abstract class. The second method of creating an empty function, does not do that.


In the above code , Base class becomes abstract class when = 0 (i.e) Base::foo() a pure virtual function (denoted by "= 0"). *

A class is abstract if it contains at least one pure virtual function.

No instances of an abstract class may be created, nor may an abstract class be used as a function argument or return type. Abstract class pointers and references are always legal. Typically an abstract class is used just as in the example above, to serve as a base and allow for manipulation via pointers or references that actually refer to instances of derived types.

The second method of creating an empty function, does not do that.

Ref: http://www.glenmccl.com/tip_033.htm

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜