• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Ubermeowmix

C++ create an array of nested class objects in a class

12 posts in this topic

Can this be done or am I clutching at straws?
 
I just want a class that uses the constructor to initialize an array of nested class objects.


class GenObjectClass
{
public:
class cTroopObj
{
public:
cTroopObj () { iTroopSize++; }
~cTroopObj () { iTroopSize--; }

void fInitObj();

private:
int miType,
miHealth,
miRally,
miSpeed,
miXloc,
miYloc,
miZloc;
};

private:
static int iTroopSize;

public:
static int siN; //keep track of objects
static cTroopObj mcaTroops[MAX_TROOPS];

void SetupObj();

GenObjectClass () { siN++; SetupObj(); }
~GenObjectClass () { siN--; }
};

void SetupObj()
{
//set up the troops
for (int i = 0; i < 4; ++i)
{
GenObjectClass::mcaTroops[i] = new GenObjectClass::cTroopObj;
}
};
0

Share this post


Link to post
Share on other sites
You don't need SetupObj(). The objects in the arrays will be created when the array is created.
2

Share this post


Link to post
Share on other sites

You forgot an asterisk (mcaTroops must be a pointer array): static cTroopObj* mcaTroops[MAX_TROOPS];
 

Other than that, I don't see why this wouldn't work. If you want to store objects instead of pointers, that will of course work too, but then you should not assign objects that you allocate on the heap (and you'd need an overloaded operator=).

 

And... that too (good catch):

You don't need SetupObj(). The objects in the arrays will be created when the array is created.

...if you want to create MAX_TROOPS objects in every GenObjectClass object, then just remove SetupObj.

Edited by samoth
0

Share this post


Link to post
Share on other sites

I think this breaks some good programming guidelines...

 

You want the troops to be stored and created by an outside entity.

 

eg.

 

Troop

TroopContainer

*Container<Troop>

*addTroop(Troop troop)

0

Share this post


Link to post
Share on other sites
Awesome thanks guys.

Just a few last questions, do I need to "delete mcaTroops;" in the destructor?
As soon as I use a pointer the memory is allocated on the heap isn't it, will it stay in scope whilst the GenObjectClass object; still exists!

And do I need to declare the object as a pointer to keep it 'alive' (GenObjectClass* object;) within the scope of the main function? deleting that when it is also not needed in the code.
0

Share this post


Link to post
Share on other sites
I want an array of nested class objects to be stored in the main class objects array, they are then created and detroyed by the function calls of the class they are nested in.

Troop
TroopContainer
*Container<Troop>
*addTroop(Troop troop)

Edited by Ubermeowmix
0

Share this post


Link to post
Share on other sites
You should only [i]delete[/i] what you have created with [i]new[/i]. Is mcaTroops supposed to be static, meaning it only exists one such array that will stay alive until the end of the program, or do you want each GenObjectClass to have its own mcaTroops array?
2

Share this post


Link to post
Share on other sites

You should only [i]delete[/i] what you have created with [i]new[/i].

So for the following line how do I reference back to this object once created? or do I just assign the array slot to zero?
GenObjectClass::mcaTroops[i] = new GenObjectClass::cTroopObj;

Is mcaTroops supposed to be static, meaning it only exists one such array that will stay alive until the end of the program, or do you want each GenObjectClass to have its own mcaTroops array?

Ah I seem to have mistaken the use of static then, I didn't realise it was till program death, I thought it was in the scope of the objects lifespan.

yes, each GenObjectClass to have its own mcaTroops array. Edited by Ubermeowmix
0

Share this post


Link to post
Share on other sites

It looks as though you're trying to create a horrific mashup between a freelist and a monostate? There are reasons why I could see it being useful in some high performance contexts, or some really underpowered architectures, but I suspect this will end badly in this case (static variables are just globals, and that's usually always a bad idea). The biggest problem you'll face is that you're going to implicitly tie together the implementations of a few classes, and code reuse will go flying out the window. But anyway.... 

 

The easiest way would be like this:

 
#include <vector>
 
class cTroops
{
public:
 
  class cTroopObj
  {
    friend class cTroops;
    cTroopObj(int type /* add more construction args if needed */ ) 
      : miType(type), miHealth(100) /* initialise remaining member vars here */ { }
    ~cTroopObj() {}
  public:
 
    /* member funcs here */
 
  private:
    int miType,
      miHealth,
      miRally,
      miSpeed,
      miXloc,
      miYloc,
      miZloc;
  };
 
  cTroups() : m_troups() {}

  void addTroup(int type /* more args if needed */) 
  {
    m_troups.push_back( cTroopObj(type /* more args if needed */) );
  }
 
  void removeTroup(size_t index)
  {
    m_troups.erase(m_troups.begin() + index);
  }
 
  cTroopObj& operator [] (size_t index) 
  {
    return m_troups[index];
  }
 
  const cTroopObj& operator [] (size_t index) const 
  {
    return m_troups[index];
  }
 
  size_t size() const 
  {
    return m_troups.size();
  }
 
private:
  std::vector<cTroopObj> m_troups;
};
 
// to use ....
cTroups troups;
 
troups.addTroup( 1 );
troups.addTroup( 2 );
troups.addTroup( 3 );
 
for(size_t i = 0; i < troups.size(); ++i)
{
  troups[i].someMemberFuncOrWhatever();
}
troups.removeTroup( 0 ); // remove first troup
 
// remaining troups will be destroyed when troups goes out of scope

 

/edit what the hell is wrong with gamedev? Why are tabs being stripped from everything?
/edit3 And newlines as well? WTF????
/edit7094  Ok, so code tags strip tabs and spaces. Source tags strip newlines. Wut?

/edit7075 F**k it. Have the screwed version.

Edited by RobTheBloke
1

Share this post


Link to post
Share on other sites
That's great ta:

Firstly I was just trying to encapsulate the code as it seemed the natural progression if I were creating objects in objects. Is it wrong to try this kind of nesting? Would I be better off just creating a separate class?

Secondly I was trying to avoid vectors as I thought that you couldn't save them in .bin files. only vars and arrays! Is that a falsehood?
0

Share this post


Link to post
Share on other sites

That's great ta:

Firstly I was just trying to encapsulate the code as it seemed the natural progression if I were creating objects in objects. Is it wrong to try this kind of nesting? Would I be better off just creating a separate class?

 

I tend to use nested classes in cases where the classes never need to be accessed publicly (i.e. they are only used in private areas of a class). It's just a stylistic thing really, and there's no real problem doing either.

 

Secondly I was trying to avoid vectors as I thought that you couldn't save them in .bin files. only vars and arrays! Is that a falsehood?

 

 

#include <cstdio>
 
void save(std::FILE* fp, const std::vector<cTroupObj>& objs)
{
 uint32_t num = objs.size();
 std::fwrite(&num, 1, sizeoff(uint32_t), fp);
 if(objs.size()) //< important! (otherwise you'll hit NULL if empty)
 {
    std::fwrite(&objs[0], objs.size(), sizeof(cTroupObj), fp);
 }
}
 
void load(std::FILE* fp, std::vector<cTroupObj>& objs)
{
 uint32_t num = objs.size();
 std::fread(&num, 1, sizeoff(uint32_t), fp);
 objs.resize(num);
 if(objs.size()) //< important! (otherwise you'll hit NULL if empty)
 {
    std::fread(&objs[0], objs.size(), sizeof(cTroupObj), fp);
 }
}
Edited by RobTheBloke
1

Share this post


Link to post
Share on other sites

Oh that's great news, I was reading one website that said .bin files don't really like vectors. Is it stable enough to use in games saves for release titles?

 

Thanks again guys, you've cleared up quite a few things there.

Edited by Ubermeowmix
0

Share this post


Link to post
Share on other sites

There is but one problem with it. When reading in the data, the constructors will be called when you call resize, and then the values will be written over with your file data. If you had 6 million troups, this may cause a (very small) slow down due to memory bandwith / CPU cache issues. If however it's just for a few troups (i.e. <10000) you'll be fine. Ultimately, you've got to look at the simplicity of using a std::vector here to add and remove troups, vs the faffery of managing that yourself. It works, It's simple, and you can spend your time worrying about the more important aspects. 

 

If the binary data you're reading in is generally going to be constant (for example all of the mesh & collision data in your level), then that could be an area where you might want to consider something else (if, and only if, you're writing a game for xbox/ps4 and expect to be loading that data off DVD). For data being loaded off hard drive, that effort isn't really going to be worth it. For data such as a save game, it definitely isn't worth it. 

0

Share this post


Link to post
Share on other sites

Firstly, a ".bin" file isn't a type, just a hint that the data is not textual and not in a well-known format.

 

You cannot write a vector's bit pattern to a file and expect it to be meaningful. This is not an issue with vector, it is an issue with any object which is not [url="http://en.wikipedia.org/wiki/Plain_old_data_structure"]Plain Old Data[/url] (POD for short). For example, writing an array of pointers directly to a file isn't meaningful.

 

RobTheBloke's code shows how to write a vector in general, write the size and write the elements. The thing to remember is that this is only legal if cTroopObj is a POD type. Now, the linked article earlier disqualifies cTroopObj:

Moreover, a POD class must be an aggregate, meaning it has no user-declared constructors, no private nor protected non-static data, no base classes and no virtual functions

 

A final note is that if you want the data files to be platform independent, you'll need to take care of the data size, padding and the "endian" nature of the data.

1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0