Fascinating C++ minutae

C++ No Comments »

A few days ago I read this post by Stan Lippman which talks about C++’s behavior when calling virtual functions from within a base class constructor. Today he has another interesting post on the same topic in which he describes the actual mechanism the compiler uses to enforce the semantics. While I was able to guess the method the compiler uses to enable the correct behavior, I didn’t realize the following consequence until Stan said it:

The vptr always has to be set within the constructor of the actual class of the object being initialized, so that in itself is a necessary overhead of the virtual mechanism. This is why bitwise copy semantics or the use of memset/memcpy is not permissible for classes in which a vptr is present.

Previously I had the presence of a copy constructor was the only reason one couldn’t use memcpy to copy an instance of a class. Naturally, I was a good boy and didn’t ever try to use memcpy even if I knew the class lacked a copy constructor. Good thing, I suppose — that would have been a hell of a bug to track down.

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in