Are array of pointers to different types possible in c++? with example please)
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With