Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Inheritance and Arrays

Status
Not open for further replies.

codegirl

Technical User
Feb 9, 2003
13
US
I have an abstract base class, call it ABC. It has two derived classes, say Derived1 and Derived2. In another class, I need an array of objects of either Derived1 or Derived2. The problem is I don't know if the array elements should be of type Derived1 or Derived2 until run time. (I have a variable called "mode", and the value of mode determines if the array should contain Derived1 or Derived2 objects.) I can't seem to create an array of ABC pointers since you can't create instances of an abstract class. So how can I create this array?

Thank you!!
 
The problem here is that you must be making some mistake while declaring the ABC type pointer. It is possible to create pointers of abstract classes but you cannot create/instantiate objects of such classes. This means that you can use pointer of abstract classes for polymorphism.

ABC* abcPtr;
if(mode == 1)
abcPtr = new Derived1();
else
abcPrt = new Derived2();

try using the keywork "new" because it will dynamically create the object and return the pointer for the correct type. If the syntax might be wrong because I'm new to C++. Btw defering declaration of objects until runtime is called late binding or dynamic binding.

Furqan

YEH GHAZI YEH TERAY PUR-ASRAR BANDAY
 
please translate just out of curiosity

YEH GHAZI YEH TERAY PUR-ASRAR BANDAY

tomcruz.net
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top