Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are array of pointers to different types possible in c++?

Are array of pointers to different types possible in c++? with example please)

like image 231
SomeUser Avatar asked Oct 16 '09 18:10

SomeUser


People also ask

Can you have an array of different types in C?

Array in C are of two types; Single dimensional arrays and Multidimensional arrays. Single Dimensional Arrays: Single dimensional array or 1-D array is the simplest form of arrays that can be found in C.

Can pointers point to different types?

The pointers can point to any type if it is a void pointer. but the void pointer cannot be dereferenced. only if the complier knows the data type of the pointer variable, it can dereference the pointer and perform the operations. Save this answer.

Can you make an array of pointers in C?

An Array of Pointers in C. When we require multiple pointers in a C program, we create an array of multiple pointers and use it in the program. We do the same for all the other data types in the C program.

Can you have an array of pointers?

We can make separate pointer variables which can point to the different values or we can make one integer array of pointers that can point to all the values.


1 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);
like image 197
RC. Avatar answered Oct 22 '22 14:10

RC.