Jump to content

  • Log In with Google      Sign In   
  • Create Account

FREE SOFTWARE GIVEAWAY

We have 4 x Pro Licences (valued at $59 each) for 2d modular animation software Spriter to give away in this Thursday's GDNet Direct email newsletter.


Read more in this forum topic or make sure you're signed up (from the right-hand sidebar on the homepage) and read Thursday's newsletter to get in the running!


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


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
13 replies to this topic

#1 Ubermeowmix   Members   -  Reputation: 337

Like
0Likes
Like

Posted 24 May 2013 - 04:05 AM

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;
}
};
If you get near a point, make it!

Sponsor:

#2 Wooh   Members   -  Reputation: 653

Like
2Likes
Like

Posted 24 May 2013 - 04:32 AM

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

#3 samoth   Crossbones+   -  Reputation: 5036

Like
0Likes
Like

Posted 24 May 2013 - 04:33 AM

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, 24 May 2013 - 04:38 AM.


#4 Waterlimon   Crossbones+   -  Reputation: 2641

Like
0Likes
Like

Posted 24 May 2013 - 05:17 AM

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)


o3o


#5 Ubermeowmix   Members   -  Reputation: 337

Like
0Likes
Like

Posted 24 May 2013 - 05:20 AM

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.
If you get near a point, make it!

#6 Ubermeowmix   Members   -  Reputation: 337

Like
0Likes
Like

Posted 24 May 2013 - 05:22 AM

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, 24 May 2013 - 05:23 AM.

If you get near a point, make it!

#7 Wooh   Members   -  Reputation: 653

Like
2Likes
Like

Posted 24 May 2013 - 08:50 AM

You should only delete what you have created with new.

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?

#8 Ubermeowmix   Members   -  Reputation: 337

Like
0Likes
Like

Posted 24 May 2013 - 04:08 PM

You should only delete what you have created with new.

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, 24 May 2013 - 04:14 PM.

If you get near a point, make it!

#9 RobTheBloke   Crossbones+   -  Reputation: 2341

Like
1Likes
Like

Posted 24 May 2013 - 05:47 PM

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, 24 May 2013 - 06:04 PM.


#10 Ubermeowmix   Members   -  Reputation: 337

Like
0Likes
Like

Posted 24 May 2013 - 06:37 PM

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?
If you get near a point, make it!

#11 RobTheBloke   Crossbones+   -  Reputation: 2341

Like
1Likes
Like

Posted 25 May 2013 - 03:50 AM

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, 25 May 2013 - 03:52 AM.


#12 Ubermeowmix   Members   -  Reputation: 337

Like
0Likes
Like

Posted 25 May 2013 - 05:03 AM

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, 25 May 2013 - 05:03 AM.

If you get near a point, make it!

#13 RobTheBloke   Crossbones+   -  Reputation: 2341

Like
0Likes
Like

Posted 25 May 2013 - 05:22 AM

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. 



#14 rip-off   Moderators   -  Reputation: 8762

Like
1Likes
Like

Posted 25 May 2013 - 05:24 AM

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 Plain Old Data (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.






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS