Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One pointer, two different classes in c++

Suppose I have two structures a and b, each hold several variable in them (most of the variable are c++ core types but not all).

Is there a way to create a a pointer named c that can point to either one of them? Alternatively, is there a way to create a set that can hold either one of them?

Thanks

like image 728
Yotam Avatar asked Sep 05 '11 07:09

Yotam


People also ask

Can a pointer point to another class?

It is true that a pointer of one class can point to other class, but classes must be a base and derived class, then it is possible. To access the variable of the base class, base class pointer will be used.

Can a pointer point to multiple?

Yes. A pointer p to type T can point to a single T , or to an array of T .

Can an object have two classes?

A class merely defines what the operations are, among other things. The only way to pass the same object to two functions of different classes is if one class inherits from the other, and the Object is an instance of the inherited class.

Can two pointers have same name?

You cannot do this kind of cast. Especially int to double as their size is different.


1 Answers

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 of the base-class can point to any sub-class. Note that this way you can only access elements that are part of the base-class through that 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; // legal
    p.b = 1; // illegal, cannot access members of sub-class
    p = new Sub2; // can point to any subclass
}

What you are trying to achieve is called polymorphism, and it is one of the fundamental concepts of object oriented programming. One way to access member of the subclass is to downcast the pointer. When you do this, you have to make sure that you cast it to the correct type:

static_cast<Sub1*>(p).b = 1; // legal, p actually points to a Sub1
static_cast<Sub2*>(p).c = 1; // illegal, p actually points to a Sub1

As for your second question, using the technique described above, you can create a set of pointers to a base-class which can then hold instance of any of the subclasses (these can also be mixed):

std::set<Base*> base_set;
base_set.insert(new Sub1);
base_set.insert(new Sub2);
like image 76
Björn Pollex Avatar answered Sep 29 '22 04:09

Björn Pollex