Calling a function of a sub-class when only the main class is known

elloco999

Well-known member
Joined
Dec 21, 2004
Messages
49
Programming Experience
5-10
Hi,

I'm trying to write a simple game. In this game the player has an inventory, that can contain several objects. An object is a class thet inherits from base class Object_Base. In OjectBase the objects name, weight and price are stored.
A ligth armor is such an object. A light armor is an instance of the class Armor. The values that are specific for an armor are stored in this class, such as armor hitpoints.

To be able to store several instances of different classes (such as a light armor, a medium armor and an Glock 19 (class Weapon)) I have declared an array of class Object_Base.
Now, if I want to get the name of an object I use: Objects(0).GetName() (function of class Object_Base), but to get the hitpoints left of the light armor I will need to call lightArmor.GetHitPoints()
So, here's my question: How can I call a function of class armor when the armor in question is in an array of class Object_Base? If I call Objects(0).GetHitPoints() It doesn't work (because it's not an function of Object_Base)

Greetz,
El Loco
 
Create another variable (for example: Dim amr as armor) and set it equal to the index of the array [arm=Objects(0)]. Then call the function [arm.GetHitPoints].
 
Ok, but this means you have to know what the object is (weapon or armor). Objects(0) can be any object. So I'll just add a variable to Object_Base stating the type of object. That should work.

Thanks!
El Loco
 
Hi All...

I'm developing a VB.Net application... i would like to do the following...
1. Menus (including main and all submenus) should be dynamically loaded from the databases. (sql server)
2. For that i need the database structure as well as coding

Kindly do the needful...
 
Regarding weather Object(0) is a weapon or armor:

The idea regarding a property stating the type of object is a good one. You could use enums for that.

You could also check the type of the Object first using an If or Select statement (If TypeOf Object(0) Is Armor then ...), then call the GetHitPoints if the object is of the type armor.

Pad:
Welcome to VBDotNetForums :).
Please submit a new post and I'm sure someone will try to help.
 
Back
Top