Are array of pointers to different types possible in c++? with example please)
-
It wouldn't be an array, it would a type-erasing container. Array by definition (given way before existence of C and C++) is a collection of same-type objects. Relevant: stackoverflow.com/questions/11169418/numpy-style-arrays-for-cSwift - Friday Pie– Swift - Friday Pie2024-08-17 09:37:46 +00:00Commented Aug 17, 2024 at 9:37
8 Answers
Usually if you want to have a collection of different "types" of pointers, you implement it in a way where they derive off a base class/interface and store a pointer to that base. Then through polymorphism you can have them behave as different types.
class Base
{
public:
virtual void doSomething() = 0;
};
class A : public Base
{
void doSomething() { cout << "A\n"; }
};
class B : public Base
{
void doSomething() { cout << "B\n"; }
};
std::vector<Base*> pointers;
pointers.push_back(new A);
pointers.push_back(new B);
2 Comments
dynamic_cast is, basically, a switch over types. And Switching over types is just a sign of (irrational) fear of polymorphism. When you're tempted to do that, use virtual functions instead.An array of pointers to void has already been mentioned. If you want to make it practical and useful, consider using an array (or, better, vector) of boost::any.
Comments
C++ is C with more stuff. So if you want to do it the C way, as above you just make an array of void pointers
void *ary[10]; ary[0] = new int(); ary[1] = new float();
DA.
If you want to do things the object oriented way, then you want to use a collection, and have all the things you going to be adding to the collection derive from the same base object class that can be added to the collection. In java this is "Object", C++ has no base object built in, but any collection library you use will have such a thing that you can subclass.
8 Comments
void*, the runtime system gives you nothing to find out what it points to.... if you use a void *, it's easy ;-)
3 Comments
Yes. Two ways:
• Pointers to a base class type, which point to objects of types derived from that base type.
• Untyped void * pointers, which must be cast manually to the actual object types they point to.
The first approach is standard object-oriented programming.
The second approach is useful for low-level programming (e.g., device drivers, memory management libraries, etc.), and is considered dangerous and suitable only for programmers who know exactly what they're doing. Obviously, it requires additional bookkeeping info to tell you what each pointer's real type is.
Comments
Since nowadays it's advised to use smart pointers I decided to rewrite the first answer using them. Here is the code you would change. Pros of using smart pointers is that it is more memory safe than raw pointers.
std::vector<std::shared_ptr<Base>> pointers;
pointers.push_back(std::make_shared<A>());
pointers.push_back(std::make_shared<B>());