Creating Classes Dynamically

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

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