开发者

cpp inheritance questions

What other reason apart from inheritance should a class need to have its functions as virtual?

What happens during run time where a base class is inherited and the derived class doesn't implement few of the base class function and a third class calls that undefined methods which are defined as virtual in base. seg fault or will it call the base class function?

What should I do if I don't want to define all the functions in my base class on my deriv开发者_JAVA百科ed class but still have the necessary inheritance in place?


What other reason apart from inheritance should a class need to have its functions as virtual?

There is no reasonable usage for having a virtual function, if you are not dealing with inheritance. Both are meant for each other.

What happens during run time where a base class is inherited and the derived class doesn't implement few of the base class function and a third class calls that undefined methods which are defined as virtual in base. seg fault or will it call the base class function?

If Derived class don't make any declaration about the virtual function at all in its body, then (immediate) base class virtual functions are called with derived class object. On the other hand, if you simply declare virtual function in derived class but do not define it then it's a linker error. No segmentation fault.

What should I do if I don't want to define all the functions in my base class on my derived class but still have the necessary inheritance in place?

Though this is unclear, I would say, you simply don't declare/define virtual function (which you don't want) in derived class. It will use base class virtual functions.


If you do not reimplement a virtual method, a caller will call the base class one. This is sort of the point of using inheritance, IMO.

If you do not want a base class to implement a virtual method, you can declare it like this:

class Demo {
    void foo() = 0;
};

This is what is called an abstract class. Note that you cannot create an instance of such a class. Any class which inherits from Demo must implement foo(), or it will also be an abstract class, and as such not instansiable.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜