Virtual functions in constructors, why do languages differ?

前端 未结 6 1553
攒了一身酷
攒了一身酷 2021-01-04 09:56

In C++ when a virtual function is called from within a constructor it doesn\'t behave like a virtual function.

I think everyone who encountered this behavior for the

6条回答
  •  爱一瞬间的悲伤
    2021-01-04 10:20

    I have found the C++ behavior very annoying. You cannot write virtual functions to, for instance, return the desired size of the object, and have the default constructor initialize each item. For instance it would be nice to do:

    BaseClass() { for (int i=0; i

    Then again the advantage of C++ behavior is that it discourages constuctors like the above from being written.

    I don't think the problem of calling methods that assume the constructor has been finished is a good excuse for C++. If this really was a problem then the constructor would not be allowed to call any methods, since the same problem can apply to methods for the base class.

    Another point against C++ is that the behavior is much less efficient. Although the constructor knows directly what it calls, the vtab pointer has to be changed for every single class from base to final, because the constructor might call other methods that will call virtual functions. From my experience this wastes far more time than is saved by making virtual functions calls in the constructor more efficient.

    Far more annoying is that this is also true of destructors. If you write a virtual cleanup() function, and the base class destructor does cleanup(), it certainly does not do what you expect.

    This and the fact that C++ calls destructors on static objects on exit have really pissed me off for a long time.

提交回复
热议问题