Creating Classes Dynamically

One reader posted the following question: “I have two classes that have the same member functions and data members. However, the member functions perform different operations. Why can’t I do something like this:”

                       void* pCls;                       if (cond == true)    pCls =(Class1 *) new Class1;  else    pCls = (Class2 *) new Class2;  pCls->CommonFunc(); //compiler error

On the face of it, there are many reasons why this code snippet refuses to compile (and even if it did compile, it would probably manifest undefined behavior at runtime). Notwithstanding that, dynamic creation of objects is a fundamental feature of object-oriented programming. How can you achieve the desired effect in well-formed C++?

First, the fact that the two classes have member functions with identical names but different functionality cries for inheritance and virtual member functions. This is done by deriving one class from the other or by deriving both of them from an abstract base class. Secondly, void* should be replaced with a pointer to the base class. Not only is this safer but it also eliminates to need for brute-force casts. The result should look like this:

    class Base {public:   virtual void CommonFunc() = 0;};class Class1 : public Base{public:   void CommonFunc(); //implementation };class Class2 : public Base {public:   void CommonFunc();//implementation};Base * pb;if (cond == true)    pb = new Class1;else    pCls = new Class2;pCls->CommonFunc(); //now fine
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may