Computing.Net > Forums > Programming > C++ help for a newbie

C++ help for a newbie

Reply to Message Icon

Original Message
Name: bdcrisp
Date: May 22, 2004 at 04:07:00 Pacific
Subject: C++ help for a newbie
OS: win xp
CPU/Ram: athlon 2200+
Comment:

I'm having a bit of trouble using classes. My idea was to setup a common (parent) class called gameobjects, with properties and functions that could apply to all subclass objects. I wanted then to define sample subclasses, called containers, weapons. These would share the common properties/methods of the gameobjects class in addition to either a contents array (for containers), or a weaponstrength integer (for weapons). I prototyped the classes as follows:

#include<iostream.h>
#include<string.h>

class gameobjects
{
public:
string description;
int location;
void describe();
};
class container:public gameobjects
public:
string contents[10];
};
class weapon:public gameobjects
public:
int weaponstrength;
};
// next i set up a few simple assignments in
// the main routine:

int main()
{
container cabinet;
cabinet.description="A wooden cabinet";
cabinet.describe();
weapon gun;
gun.description="An old rifle";
gun.describe();

system("PAUSE");
return 0;
// i wanted to be able to use the gameobject //parent class's describe function to print //the description property of any object //declared in a subclass of gameobjects, such //as container cabinet, drawer or
//weapon gun, knife;
// this type of thing
// but was unsure how to prototype or define // this function in the code


Report Offensive Message For Removal

Response Number 1
Name: Don Arnett
Date: May 22, 2004 at 10:38:04 Pacific
Subject: C++ help for a newbie
Reply: (edit)

Since description and describe() are both part of the parent class and it doesn't appear that you want/need to have describe() do different actions for the child classes, there is nothing special to do.

Just define the describe() method and then use it.

void gameobjects::describe() {
cout << description;
}

That should work with the code that you have above.



Report Offensive Follow Up For Removal







Use following form to reply to current message:

   Name: From My Computing.Net Settings
 E-Mail: From My Computing.Net Settings

Subject: C++ help for a newbie

Comments:

 


  Homepage URL (*): 
Homepage Title (*): 
         Image URL: 
 
Data Recovery Software