Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: All
Nov 6, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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;
    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 
  virtual void CommonFunc() = 0;
class Class1 : public Base
  void CommonFunc(); //implementation 
class Class2 : public Base 
  void CommonFunc();//implementation

Base * pb;
if (cond == true)
    pb = new Class1;
    pCls = new Class2;
pCls->CommonFunc(); //now fine
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date