Skip to main content
gamedev.net
🔒 Locked

C++ Classes and Structures and "fast" code

Started by Hybris May 11, 2009 at 1:59 PM 25 replies 4.5k views
Original Post
Hybris
Hybris
Hi all, I'm going to learn C++ and what better way of learning than making a game :) I'n no totally inexperienced since I made some small textbased games in Ada and visual basic. However since I'm still pretty new to object orientation I would like to learn it good from the start and with good I mean fast code that is accepted in the game industry (ok Im not talking assembler fast but atleast somewhat optimized). I heard that for example classes shouldn't take to many parameters and I'm wondering what the "limit" is and what about structures, are there any limits to those aswell? What about nested structures, are those slower or faster than ordinary structures? For example if I want to make a RPG and want to spawn enemies easy should i make a class like this class enemy (int strength, int physics, int intelligence, int endurance, int hitpoints, int ...., .... ,....) and then to spawn it I type like spawn(x_coord, y_cord) enemy(100, 20, 99, 45, 34, 543, 3,4,...,...,...,...) or is it better to use alot of smaller classes that only take a few parameters as input? Yes I know the code ^^ wont work ;) Also if I want to make like a strategy game where you run a small country and fight other countries, would it be a good way to make country a data structure something like struct country { float money; int attackpoints; int researchpoints; int smallbuildingA; int mediumbuildingA; int largebuildingA; int smallbuildingB; int medbuildingB; int largebuildingB; int smallbuildingC; ... .. . }; or would it be better to make several structures like struct building { int small buildingA .. . . int largebuildingC}; and then use the structure building inside the structure country....? Could someone (if you are still awake) give me some pointers or general guidelines regarding classes and structures, small and specialised vs big and generialised? Also I guess theres things like lean production in the game industry an perhaps its better to write slower code thats easy to reuse than fast code thats more specific? But Im still somewhat in the amiga500 scene mindset where fast code >>>>> anything else :O
NotAYakk
NotAYakk
struct foo {  int a;  double b;  char c;};struct bar {  int a;  double b;};struct baz {  bar x;  char c;};

foo and baz are identical in binary layout. The names of the members are different.

"unfolding" a struct into a parent struct has no impact on the binary layout of the parent struct.

By breaking things up into smaller chunks, however, you can write functions that take only part of the parent structure and do things with it. This can be highly useful.

Big structures are hard to understand. In a successful program, you will be spending more time debugging and maintaining it than you do writing it. So write your code to be understood.

The same holds for ridiculous lists of arguments. They are hard to understand. You are probably better off with a file describing the data. If you must make it static data, you can write a program that takes the description file and outputs a .cpp file with the creation code.
Hybris
Hybris
44 views 0 replies O.o

Any input would be greatly appriciated.

Edit: Oh 1 reply while writing this post :) Thank You ^
Edit 2: About the foo and baz I got it thanks, about the part about classes with tons of parameters I see the problem when using the class but im very skilled with // usage :O. I tend to write more explanations than code heh. But I get it and usually make functions with few intuitive parameters... however will the speed of the program be slower if i use alot of parameters as input for the classes?
Captain P
Captain P
Quote:
Original post by Hybris
I'n no totally inexperienced since I made some small textbased games in Ada and visual basic. However since I'm still pretty new to object orientation I would like to learn it good from the start and with good I mean fast code that is accepted in the game industry (ok Im not talking assembler fast but atleast somewhat optimized).

Optimization is best done after profiling - that is, you write code (of course, you should think ahead, but you shouldn't get all too obsessed over it) and then you check if it's fast enough. On modern-day systems, and if you're not writing too complicated things (which, as a beginner, you shouldn't), you'll hardly ever run into trouble (or you're doing something in an obviously inefficient manner). Either way, if performance is a problem, you should determine what causes it, and fix those parts first.

Also, different platforms require different mindsets. On a PC, I'd prefer a high-level scripting language over a low-level one for many things. It's trading some performance for development speed and flexibility - a trade-off that is much more easily made now than it was years ago.

Quote:
I heard that for example classes shouldn't take to many parameters and I'm wondering what the "limit" is and what about structures, are there any limits to those aswell? What about nested structures, are those slower or faster than ordinary structures?

I wouldn't worry about speed here, but about clarity, manageability, aspects like that. Object-orientated development wraps things up into small, manageable chunks, and allows you to work on higher levels - instead of working with ints, bytes and the like, you start working with the objects you designed - Player, Building, Country, and so on.

Quote:
For example if I want to make a RPG and want to spawn enemies easy should i make a class like this

class enemy (int strength, int physics, int intelligence, int endurance, int hitpoints, int ...., .... ,....)

and then to spawn it I type like


spawn(x_coord, y_cord) enemy(100, 20, 99, 45, 34, 543, 3,4,...,...,...,...)

or is it better to use alot of smaller classes that only take a few parameters as input?

Depends on the situation, but yeah, that looks pretty ugly. You'll probably want to store those values in an external file anyway, so it's easier to tweak the gameplay. Waiting for a recompile every time gets boring quick.

Quote:
Also if I want to make like a strategy game where you run a small country and fight other countries, would it be a good way to make country a data structure something like

struct country {
float money;
int attackpoints;
int researchpoints;
int smallbuildingA;
int mediumbuildingA;
int largebuildingA;
int smallbuildingB;
int medbuildingB;
int largebuildingB;
int smallbuildingC;
...
..
.
};

Uhm, no. Buildings and things like that are typically not stored as integers. They probably - depending on your game's design - have properties of their own. How about a Building class that takes care of that? That, and small, medium and large buildings probably only differ by size, so you can make it a property of the Building class.

Quote:
Could someone (if you are still awake) give me some pointers or general guidelines regarding classes and structures, small and specialised vs big and generialised?

It's something that comes with experience, but I think you tend to think too low-level.

Quote:
Also I guess theres things like lean production in the game industry an perhaps its better to write slower code thats easy to reuse than fast code thats more specific? But Im still somewhat in the amiga500 scene mindset where fast code >>>>> anything else :O

Fast code isn't necessarily cryptic and 'single-structed' - but really, it's not that big of an issue anymore these days. Most optimizations are done at higher levels, by choosing the right algorithms and data structures. Modern compilers have become pretty good at taking care of the lowest levels, too, so you'd have to be pretty good at assembly to beat them.
Zahlman
Zahlman
Edit: Someone linked this somewhere else in Game Programming recently. It's a good read, and relevant here.

Quote:
Original post by Hybris
I'm going to learn C++


The power of the dark side compels you. ;)

Quote:
However since I'm still pretty new to object orientation


C++ is not "an OO language". It is not even primarily about OO. It simply offers reasonably good support for OO (much better than C, anyway, where you have to implement polymorphic dispatch yourself). Further, a quick check with Google indicates that OOP is commonly done in both languages you already know. So you are learning two completely separate things here: a new language, and a new design paradigm.

Quote:
I would like to learn it good from the start and with good I mean fast code


That's strange, because "fast code" is near the bottom of the list of things that experienced developers generally mean by "learning a language well".

Quote:
that is accepted in the game industry


Why do you care what is "accepted in the game industry"?

Quote:
I heard that for example classes shouldn't take to many parameters


That has nothing to do with performance; it has to do with organization.

Quote:
and I'm wondering what the "limit" is and what about structures, are there any limits to those aswell?


You shouldn't let your room get too messy. Is there a "limit" on how many things you can leave lying around?

Quote:
What about nested structures, are those slower or faster than ordinary structures?


Accessing elements of a structure involves adding a known offset to the address of the structure. Nested structures don't cost anything if they're directly embedded, because then you just add another known offset, and the two known offsets get summed ahead of time by the compiler. If you have a pointer to another structure, though, then that pointer will have to be dereferenced (and an offset added again, presumably). One operation is slower than no operations. Similarly, if you stick your hand out the car window, and don't increase the gas supply, the car will slow down a tiny bit.

Quote:
For example if I want to make a RPG and want to spawn enemies easy should i make a class like this


Do make a class to represent the enemy, yes. How to organize the data contents depends on what the enemy has to do, and is not something that can simply be explained - it must be taught, and refined over years of experience. But fortunately, you already have some experience. You have used some kinds of data structures in your VB and Ada programming, yes? Especially in Ada, it seems impossible to avoid.

Quote:

Also if I want to make like a strategy game where you run a small country and fight other countries, would it be a good way to make country a data structure something like

...

or would it be better to make several structures like

...

and then use the structure building inside the structure country....?


1) You don't want to make things like buildingA, buildingB, etc. You have at least heard of arrays, right? Or more generally, of containers (such as a linked list, an associative array, a vector...)?

2) Structures represent data types. If you make a Building structure, it does not exist for the purpose of containing buildings. It exists for the purpose of describing what a building is. (an int does not describe a building.) It might include some data, for example, that indicates the size of the building.

Then, you make a container of Buildings, and have that container as a data member of the Country.

Quote:
Could someone (if you are still awake)


1) Gamedev.net members live all around the world.
2) This is a forum; it is not for real-time communication.

Quote:
But Im still somewhat in the amiga500 scene mindset where fast code >>>>> anything else :O


Wait, they use Ada and VB in the "scene"? O_O

[Edited by - Zahlman on May 11, 2009 3:14:04 PM]
Hybris
Hybris
Original post by Captain P
Original post by Hybris
Quote:

Optimization is best done after profiling - that is, you write code (of course, you should think ahead, but you shouldn't get all too obsessed over it) and then you check if it's fast enough. On modern-day systems, and if you're not writing too complicated things (which, as a beginner, you shouldn't), you'll hardly ever run into trouble (or you're doing something in an obviously inefficient manner). Either way, if performance is a problem, you should determine what causes it, and fix those parts first.

Yeah I know I will probably have to go back and fix some parts of the code if nessecary and use better algorithms.. I was more looking for general things to think of when programming not to get caught in bad habits (like i did in basic where i often used sloppier code because it was faster but i knew it would slow down the speed of the program (altough i didn't do anything too complicated that needed top speed back then, but now when im gonna make cryengine 2...) nah its just for sports and to have it with me incase i need to use faster code in the future. since im learning c++ I might aswell learn how to use it efficently from the start since it takes little extra efforet but if i get use to do it in a "slow way" it will take alot of effort to relearn (atleast thats how i work).

Quote:

Also, different platforms require different mindsets. On a PC, I'd prefer a high-level scripting language over a low-level one for many things. It's trading some performance for development speed and flexibility - a trade-off that is much more easily made now than it was years ago.

Yeah, but for me its not about making a game. I want to understand the language, what affect the speed of the code execution and stuff like that. In the future I think i will make smaller fast running applications and perhaps a mix of c++ and assembly. The game part is just a fun way to learn the basics of the language. (((Like so many other ppl my dream is to construct a mmorpg ala wow but I know that wont happen so I will pursue my other dream instead, to make a small robot which eventually will involve programming of motors, sensors and AI. (I made some very simple lowlvl (read 010101) programming for machines a couple of years ago).)))


Quote:

I wouldn't worry about speed here, but about clarity, manageability, aspects like that. Object-orientated development wraps things up into small, manageable chunks, and allows you to work on higher levels - instead of working with ints, bytes and the like, you start working with the objects you designed - Player, Building, Country, and so on.

Aye i get the idea, but first I want to learn how to construct those chunks in a good (and fast running code) way.

Quote:

Depends on the situation, but yeah, that looks pretty ugly. You'll probably want to store those values in an external file anyway, so it's easier to tweak the gameplay. Waiting for a recompile every time gets boring quick.

Yeah but those values need to go into the class or function or whatever at some point or another (either if i call the functioo/class with them direcly in the main program like Uglyenemy1(10,10,23,111,323.....) or if i hve them in an external file right? With the file i can compile my program and then just notepad the file with the numbers to change the property of the enemy but in the end somehow all those numbers will be put into the class right? I was wondeing if having that much parameters will make the class execution go slower than if i somehow use alot of different classes and split it up for example have a class
head(int facing, int hitpoints){
check does he see you;
if hitpoints<0 return you/enemy...whatever called this is dead;};
^^ this brings up another question.. is there any difference in speed when using different checks like is:
if i=5 as fast as writing i<6 ??

Quote:
;

Uhm, no. Buildings and things like that are typically not stored as integers. They probably - depending on your game's design - have properties of their own. How about a Building class that takes care of that? That, and small, medium and large buildings probably only differ by size, so you can make it a property of the Building class.


Well it was just an example, i was thinking of numbers of different buildings in the game like:
Country sweden have 1 small powerplant, 3 nuclear powerplant, 4 small barracs, 3 large barracks....

Quote:

It's something that comes with experience, but I think you tend to think too low-level.

yes I do, but I need to understand the low level before I go to a higher level. I understand its not the optimal way for working with huge games or if you are a part of a large team... but its mostly for myself and for sports... when I understand the low level I can make nice fast algoritms wrapped up in easily managebly chunks...

Quote:

Fast code isn't necessarily cryptic and 'single-structed' - but really, it's not that big of an issue anymore these days. Most optimizations are done at higher levels, by choosing the right algorithms and data structures. Modern compilers have become pretty good at taking care of the lowest levels, too, so you'd have to be pretty good at assembly to beat them.

Yeah the compilators are pretty good these days. Maby im worrying too much :O

Anyway thank You for taking the time.



Hybris
Hybris
Quote:
Original post by Zahlman


Quote:

The power of the dark side compels you. ;)

Father???? O.o

Quote:
C++ is not "an OO language". It is not even primarily about OO. It simply offers reasonably good support for OO (much better than C, anyway, where you have to implement polymorphic dispatch yourself). Further, a quick check with Google indicates that OOP is commonly done in both languages you already know. So you are learning two completely separate things here: a new language, and a new design paradigm.

Yes and yes... im sloppy with words... sometimes you have to read what i mean not what i write

Quote:
That's strange, because "fast code" is near the bottom of the list of things that experienced developers generally mean by "learning a language well".

Didn't know that, I thought it was important to have fast code. I understand the value of easily manageble code and a good structure so other can follow your code... but fast code doesnt mean you cant have a good structure...

Quote:
why do you care what is accepted in the game industry


You never know about the future... The game industry is (or atleast was) known for having fast code.

[quote

That has nothing to do with performance; it has to do with organization.
]

I once heard that alot of parameters could slow down the execution but i might have misunderstood.

Quote:
You shouldn't let your room get too messy. Is there a "limit" on how many things you can leave lying around?

Accessing elements of a structure involves adding a known offset to the address of the structure. Nested structures don't cost anything if they're directly embedded, because then you just add another known offset, and the two known offsets get summed ahead of time by the compiler. If you have a pointer to another structure, though, then that pointer will have to be dereferenced (and an offset added again, presumably). One operation is slower than no operations. Similarly, if you stick your hand out the car window, and don't increase the gas supply, the car will slow down a tiny bit.

Not even the darkside would help you in my room O.o

Quote:
Do make a class to represent the enemy, yes. How to organize the data contents depends on what the enemy has to do, and is not something that can simply be explained - it must be taught, and refined over years of experience. But fortunately, you already have some experience. You have used some kinds of data structures in your VB and Ada programming, yes? Especially in Ada, it seems impossible to avoid.

Yes i have used structures before.

Quote:



1) You don't want to make things like buildingA, buildingB, etc. You have at least heard of arrays, right? Or more generally, of containers (such as a linked list, an associative array, a vector...)?

2) Structures represent data types. If you make a Building structure, it does not exist for the purpose of containing buildings. It exists for the purpose of describing what a building is. (an int does not describe a building.) It might include some data, for example, that indicates the size of the building.

Then, you make a container of Buildings, and have that container as a data member of the Country.

Yeah i replied to the previous post.. I just used it as an example.. I had my mindset more on a textbased game where the structures would be predefined like small powerplants, nuclear powerplant..barracks and so on and the int structure a would just hold a number how many for example small pwerplants that country had.

Quote:


1) Gamedev.net members live all around the world.
2) This is a forum; it is not for real-time communication.

O.o I didn't know *rolls eyes*. I thoght if you fell asleep while reading my post...
Quote:
Wait, they use Ada and VB in the "scene"? O_O

No they used assembly.. move to blitter and stuff like that... I wasn't very into it by then but i had 3 classmates that used the words blitter and mov in atleast 92,3% of the sentences. I just remember how important it was with fast code...back then.

XTAL256
XTAL256
Quote:
Original post by Hybris
I just remember how important it was with fast code...back then.

Yes, exactly, Back then. Now it is different. Computers can do more than 2 operations a second and aren't the size of an average house. The sooner you stop worrying about execution speed, letting the compiler handle that, and getting on with actually designing manageable code, the better.
A lot of people frequently debate whether low-level C or high-level OO is better but these people seem to come from very different eras. As programs get bigger and more complicated it is absolutely necessary to think in a modular way where systems (e.g. classes) are designed at a high level and composed of smaller and smaller parts. Rather than having a huge structure for a country which contains everything, have Country class which contains Buildings which in turn contains other objects like Chairs and Tables (although you probably won't need those in your game). Listen to people like Zahlman, they know what they are talking about.
[Window Detective] - Windows UI spy utility for programmers
Zahlman
Zahlman
If you want a member variable to represent a count of something, then you should name it in a way that indicates that. Thus, "number_of_power_plants" or something. :)
SiS-Shadowman
SiS-Shadowman
Quote:
Original post by Hybris
Aye i get the idea, but first I want to learn how to construct those chunks in a good (and fast running code) way.


You should not worry that your code is slow but that your code is bad in terms of design. Maybe you can get an extra free cycle by doing a lot of scary stuff, but a brute force collision detection algorithm is going to cost you much more. So you should really just concentrate on getting to know the language and OOP.

Quote:

Yeah but those values need to go into the class or function or whatever at some point or another (either if i call the functioo/class with them direcly in the main program like Uglyenemy1(10,10,23,111,323.....) or if i hve them in an external file right? With the file i can compile my program and then just notepad the file with the numbers to change the property of the enemy but in the end somehow all those numbers will be put into the class right? I was wondeing if having that much parameters will make the class execution go slower than if i somehow use alot of different classes and split it up for example have a class
...

Premature optimization is the nature of evil!
Don't do that.
You want to write well designed code. And by the way, your speed of execution will mainly depend on the calculations / iterations you are doing and not on the number of variables a class has.

Quote:

yes I do, but I need to understand the low level before I go to a higher level. I understand its not the optimal way for working with huge games or if you are a part of a large team... but its mostly for myself and for sports... when I understand the low level I can make nice fast algoritms wrapped up in easily managebly chunks...

I think you'll hit a dead end soon. You can worry about low level stuff when you need to, again, read the sentence above if you don't believe me. It's just like optimizing floating point operations with SSE: If you don't do it right it ends up being slower than the easy approach, so why even bother if it's not worth it. For example: Operations with my own vector class are about 2 times slower than with the DirectX vectors, however I don't really care because a nice little octree to cut down the complexity of my collision detection is going to bring me alot more than replacing my code with SSE intrinsics.

When you build a car, will you concentrate on every little aspect of the engine before it even got wheels or would you wait until you know it's the engine that needs tweaking?
Codeka
Codeka
Quote:
Original post by Hybris
I once heard that alot of parameters could slow down the execution but i might have misunderstood.
Yes, and I really liked Zahlman's analogy: it's like sticking your hand out of the window of a moving car. The car will "slow down" but are you going to notice it? Even if everybody on the bus sticks their hand out the window at the same time, are you going to notice it?
phresnel
phresnel
Sidenote: There is no difference between classes and structs in C++, except that members of classes are private by default, and members of structs are public by default. Indeed, one can see "class" as syntactic sugar of "struct" with private members by default (or vice versa). In the end, you will only be paying for what you are using.
Hybris
Hybris
Hi all and Thank You for Your input. I was pretty sleepy yesterday and english is not my primary language so maby it sounded like "this is how I do" instead of "is this a good approach". The reason I asked in the first place is I want to learn good from the start and I know You guys are very experienced so thats why I asked you in the first place ;)

I will revise my strategy and worry less about the execution speed and instead focus more on writing code thats easy to use (/reuse) and debug instead.

Thanks all who took the time to give me some advice.

NotAYakk
NotAYakk
So writing easier to read/debug code makes your code faster.

Because the unit of 'cost' is programmer time, and you can spend programmer time on making your code faster.

If your code is prematurely optimised for speed speed speed, you will have more bugs. And those bugs will be harder to fix. And you will spend lots of time working on speed in places where speed doesn't matter.

That is why the two-phase approach: first, write your code so that it works, that it is easy to maintain and understand, and that it isn't _fundamentally_ slow.

Then find the parts that need to be faster. And rewrite them and/or modify them to be faster.

And keep an eye on algorithmic efficiency -- the 'O' behaviour of your code -- because in 'toy tests' you might do while debugging, in the real world N can get much larger, and cause what didn't slow you down to blow up in your face.

---

Ie, instead of having counts of numbers of buildings, make your country have a collection of buildings, and have each building have its own properties.

This allows each individual building to be unique.

Alternatively, you have a collection of building types and counts on each building type. Now you can create new types of buildings without changing how your engine works, but each building of a given type is identical to each other building of the same type.

These two approaches are much closer than you might think to each other.

And instead of having hard-coded 'do building turn' code that accesses a given building variable and has hard-coded strings, the building type (or instance) owns its own building description, and maybe its own properties that describe what it does on a turn.

It turns your "evaluate buildings" code from:
void evalBuilings( Nation* n ) {  n->totalEnergy += n->smallNuclearPlants*5;  n->totalEnergy += n->mediumNuclearPlants*15;  n->totalEnergy += n->largeNulcearPlants*50;  n->totalNukeWaste += ...;  ...  n->totalProduction += n->largeFactories * 50;  ...  ...}// to:ResourceResult evalBuildings( Nation* n ) {  ResourceResult result;  for( BuildingType* b = n->buildingsBegin(); b != n->buildingsEnd(); ++b)  {    result.energy += b->produceEnergy();    result.production += b->produceProduction();    result.food += b->produceFood();    result....  }  return result;}

In the first case, every change in the properties of a given building needs to be hard coded into your source code in the 'main loop' or evaluation code. Adding a new building type is a lot of work, and can cause a lot of bugs. A typo anywhere in the reams of code in that function could result in arbitrary and weird behaviour.

In the second case, adding a new kind of building consists of creating a new building type. The code is much shorter in total, and the engine code is separate from the building property code.

We treat things that are uniformly similar uniformly, and have them differ from each other in their data rather than in how code treats them directly. This makes the code simpler, and code is harder to get right than data is.
Zahlman
Zahlman
Quote:
Original post by NotAYakk
We treat things that are uniformly similar uniformly, and have them differ from each other in their data rather than in how code treats them directly. This makes the code simpler, and code is harder to get right than data is.


Simple yet useful statements like this deserve repetition. :)
Hybris
Hybris
edit: Bah tried to post my code from the laptop but it timed out then my laptop died. I'll give it a new try tomorrow when i find the powerchord to the laptop.

I noticed I'm very rusty in programming (was a couple of years ago since I did it last time and i think my brain is a little slower now than when i went to school heh).

I had some questions in the post that got lost in cyberspace regarding the evalBuildings function in NotAYakks post.

How would You define ResourceResult (I assume it is a struct) and BuildingType.

Also how would the buildingBegin() ..End() work?

Mmmf Il give it another try to upload my code and maby some kind soul could give me some hints..

[Edited by - Hybris on May 20, 2009 5:59:32 PM]
Hybris
Hybris
#include
using namespace std;

//********** START OF NATION TYPES AND CLASSES *****************
class nation {
protected:

double researchPoints;
double actionPoints;
double population;
double food;
double productionPoints;
int tanks;


public:
virtual void placebuilding() = 0;
virtual void research() = 0;
virtual void attack() = 0;
virtual void buildingsBegin() = 0;
virtual void buildingsEnd() = 0;

void setresearchPoints (double rp) {
researchPoints = rp;
}
void setactionPoints (double ap) {
actionPoints = ap;
}
void setpopulation (double po) {
population = po;
}
void setfood (double fo) {
food = fo;
}
void setproductionPoints (double pp) {
productionPoints = pp;
}

void settanks (int tn) {
tanks = tn;
}

};

class playernation : nation {
};

class computernation : nation {
};


[Edited by - Hybris on May 20, 2009 6:23:14 PM]
Hybris
Hybris

//************* START OF BUILDING TYPES AND CLASSES *************
class building { // Abstract Base class building
protected:
//Position on map. Also used to see occupied space.
double x_position;
double y_position;
double length;
double width;
double height;
public:
virtual double area() = 0;
virtual double volume() = 0;
virtual void produceEnergy() = 0;
virtual int producePopulation() = 0;
virtual void produceFood() = 0; //not set yet thats why void
virtual void produceReasearch() = 0;
virtual void produceProduction() = 0;
//placement of building
void setX(double x) { //function should be changed to bool and check if placement is occupied)
//insert space checking code here
x_position = x;
}
void setY(double y) { //same as above
//insert space checking code here
y_position = y;
}
void setL(double l) {
length = l;
}
void setW(double w) {
width = w;
}
void setH(double h) {
height = h;
}
};

class barrack : public building {
double area() { //the barrac is a rectangular shape
return (length * width);
}
double volume() {
if (height < 2.5) //if the barrack is lower than 2,5m it will be cubic style
return (length*width*height);
else
return (length*width*height-(length*width/2)); //The roof is tilted side a 1m higher than side b
}
int producePopulation() {
if (height < 2.5)
return (int (length*width*height)/3); //Population produced is a function of the buildings size
else
return (int (length*width*height-(length*width/2)));
}
};

class powerplant : public building {
double area() { //the powerplant is a rectangular shape
return (length * width);
}
double volume() {
return (length*width*height); //The powerplant is a cubic building
}
int produceEnergy() {
return (int (length*width*height)/3); //Power produced is a function of the buildings size
}
};

//*********** END OF BUILDING TYPES AND CLASSES *************

struct ResourceResult { //Structure what is produced in one turn based on current buildings.
double powerpoints;
double productionpoints;
double populationpoints;
double researchpoints;
double foodpoints;
double actionpoints;
};
struct BuildingType{ //probably totally wrong.. ask on gamedev
barrack barrack1;
powerplant powerplant1;
};


ResourceResult evaluateBuildngs (nation* n) {
ResourceResult result;
for (BuildingType* b = n->buildingsBegin(); b != n->buildingsEnd(); ++b;
result.powerpoints += b-> // end of lunchbreak continue tomorrow

};

int main(){
return 0;
};

edit: Sorry for not using sourcetags and for splitting code on 2 posts but it just wouldn't post otherwize. Maby a mod can help me with the sourcetags *pokes Zahlman*.

I don't have much sparetime to learn c++ (9-10h work, 3 dogs, a house and a gf that hates computers) so i try to learn during lunchbreaks and this is what i came up with today. But I know I didnt get the buildingType right (among others). Could someone please enlighten me. Thanks

ari556655
ari556655
One must learn how to properly mix mortar and lay bricks before endeavouring to build a house.
XTAL256
XTAL256
@Hybris: please use [source][/source] tags around the code you post, it makes it a whole lot nicer to read :)
[Window Detective] - Windows UI spy utility for programmers

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.