C++ - Objects pointers array

  • Comp Sci
  • Thread starter erezb84
  • Start date
  • #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
CompuChip
Science Advisor
Homework Helper
4,306
48
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
43
0
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
D H
Staff Emeritus
Science Advisor
Insights Author
15,415
687
Use overloading.
Code:
class Array_Class {
   add_pointer (A_1 * ptr);
   add_pointer (A_2 * ptr);
   ...
};
 
  • #5
43
0
Thanks! i think overloading is the answer!
 

Related Threads on C++ - Objects pointers array

Replies
15
Views
6K
  • Last Post
Replies
8
Views
1K
  • Last Post
Replies
2
Views
2K
  • Last Post
Replies
13
Views
2K
Replies
8
Views
4K
  • Last Post
Replies
2
Views
1K
  • Last Post
Replies
2
Views
1K
  • Last Post
Replies
8
Views
2K
Top