[ACCEPTED]-Are array of pointers to different types possible in c++?-pointers

Accepted answer
Score: 16

Usually if you want to have a collection 5 of different "types" of pointers, you implement 4 it in a way where they derive off a base 3 class/interface and store a pointer to that 2 base. Then through polymorphism you can 1 have them behave as different types.

class Base
    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);
Score: 8

An array of pointers to void has already 3 been mentioned. If you want to make it practical 2 and useful, consider using an array (or, better, vector) of 1 boost::any.

Score: 8

C++ is C with more stuff. So if you want 11 to do it the C way, as above you just make 10 an array of void pointers

void *ary[10];
ary[0] = new int();
ary[1] = new float();


If you want 9 to do things the object oriented way, then 8 you want to use a collection, and have all 7 the things you going to be adding to the 6 collection derive from the same base object 5 class that can be added to the collection. In 4 java this is "Object", C++ has no base object 3 built in, but any collection library you 2 use will have such a thing that you can 1 subclass.

Score: 3

... if you use a void *, it's easy ;-)


Score: 3

Yes. Two ways:

• Pointers to a base 13 class type, which point to objects of types 12 derived from that base type.
• Untyped 11 void * pointers, which must be cast manually to 10 the actual object types they point to.

The 9 first approach is standard object-oriented 8 programming.

The second approach is useful 7 for low-level programming (e.g., device 6 drivers, memory management libraries, etc.), and 5 is considered dangerous and suitable only 4 for programmers who know exactly what they're 3 doing. Obviously, it requires additional 2 bookkeeping info to tell you what each pointer's 1 real type is.

Score: 1

Yes; just cast your pointers in the array 4 to whatever type you want them to refer 3 to.

Alternately, you could make your array 2 an array of a union (with the union elements 1 being the differing pointer types).

Score: 0
#include <stdio.h>

int main(void)
  void * ptr[2];
  int *a;
  int b;

  ptr[0] = "[0] = \"This is a string & c does it better\", [1] = ";
  *a = 2;
  ptr[1] = a;
  b = *((int *) ptr[1]);
  printf("%s",  (char *) ptr[0] );
  printf("%i\n", b );

  return 0;


More Related questions