C++ - Objects pointers array

  • #1
43
0

Homework Statement


suppose i have class A.
now i have 2 derative classes: A_1, A_2.

i would like to create a 4'th class: Array_Class.
Array_Class will have 2 pointers array (one for each class - A_1, A_2).
i want to be able to get an object pointer from class A_1 or A_2, and place it in the right array.
how should i do it?
another importent issue: i am not allowed to use virtual functions.

The Attempt at a Solution


I thought of saving in each class (A_1, A_2) a type variable, and in Array_Class to do switch or somthing to know in which array save the pointer.
I know this is no good proggraming, but is there bettwer way to do it ? (again - without using virtual functions).

hope i was clear...
Thanks!
 

Answers and Replies

  • #2
Wait, so what you want is something like this?
Code:
class { 
  A1** a1s;
  A2** a2s;
 
  void addPointer(A* a) { 
    // add a to a1s or a2s depending on its type
  }

That is, as you say, terrible programming and any teacher giving you such an assignment should be locked away!

You should make a single array of pointers to A's, and use polymorphism, i.e. so you can call
Code:
A* a = arrayOfAs[i];
a->method();
without knowing if a is of subtype A1 or A2.
As soon as your find yourself writing checks like "if(a is of type A1) { doSomething(); } else if(a is of type A2) { doSomethingElse(); }" you should seriously reconsider your design or else you may just as well switch back to C and get rid of those pesky object-thingies.

That said, if you keep insisting on abusing the features of C++, the "a is of type A1" line in my pseudocode above can be implemented with dynamic_cast:
Code:
bool isA1 = !(dynamic_cast<A1*>(a) == null);
 
  • #3
Yes, this is the excercise we got.
and we got the instruction - not use virtual function, not use casting...
so i think even the "terrible" "a is of type A1" i can't write...
 
  • #4
Use overloading.
Code:
class Array_Class {
   add_pointer (A_1 * ptr);
   add_pointer (A_2 * ptr);
   ...
};
 
  • #5
Thanks! i think overloading is the answer!
 

Suggested for: C++ - Objects pointers array

Replies
17
Views
793
Replies
3
Views
240
Replies
3
Views
438
Replies
3
Views
608
Replies
4
Views
588
Replies
21
Views
1K
Replies
6
Views
712
Replies
2
Views
221
Replies
8
Views
253
Back
Top