The usual way to create a pointer that can point to either of the two is to make them inherit from a common base class. Any pointer to a base class can point to any subclass. Note that in this way you can access elements that are part of the base class through this pointer:
class Base {
public:
int a;
};
class Sub1 : public Base {
public:
int b;
};
class Sub2 : public Base {
public:
int c;
};
int main() {
Base* p = new Sub1;
p.a = 1;
p.b = 1;
p = new Sub2;
}
What you are trying to achieve is called polymorphism , and this is one of the fundamental concepts of object-oriented programming. One way to access a member of a subclass is to lower the pointer. When you do this, you must make sure that you apply it to the correct type:
static_cast<Sub1*>(p).b = 1;
static_cast<Sub2*>(p).c = 1;
, , , ( ):
std::set<Base*> base_set;
base_set.insert(new Sub1);
base_set.insert(new Sub2);