devxlogo

Before You Resort to Void *…

Before You Resort to Void *…

Void * can serve as a generic data pointer, yet it suffers from the well-known ailments associated with pointers: it can be NULL or a dangling pointer. Furthermore, it usually has to be cast back to its original type in order to access its data–a dangerous and sometimes costly operation if performed at run time. Luckily, C++ offers higher level mechanisms for genericity that are both safer and more efficient:

1. Templates. Templates are a better choice for generic (type-independent) algorithms and functions. In addition, they are safer since they do not involve pointer manipulations and can be checked at compile time:

 template  void  swap ( T f, T s); 

2. Inheritance. If you need a function or an algorithm that can be applied to a family of types, you may use a common base class from which all other related types are derived:

 class WindBase { public: virtual void Create()=0; virtual void Destroy() = 0; };class WindFrame: public WindBase { public: void Create(); void Destroy(); };class WindView: public WindBase { public: void Create(); void Destroy();}; };void DestroyWindow(WindBase &anyWindow); //for all objects derived from WindBase

Please note that void* should be used in very low-level operations–for example, manipulating hardware buffers or in system routines such as memset() and malloc().

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist