• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

C++ Help?

Status
Not open for further replies.

The Technomancer

card-carrying scientician
Hm, okay, I want the destructor for a class I'm writing to call the functionality of a separate object, but since destructors can't take parameters I can't pass the second object in by reference or whatever. Advice?
 

Slavik81

Member
Hm, okay, I want the destructor for a class I'm writing to call the functionality of a separate object, but since destructors can't take parameters I can't pass the second object in by reference or whatever. Advice?

If it is required at time of destruction, pass it in on construction. It it's optional, set it after construction. If this makes construction complicated and you need to construct them often, create a factory to build these things in the configuration you desire.
 

tokkun

Member
Hm, okay, I want the destructor for a class I'm writing to call the functionality of a separate object, but since destructors can't take parameters I can't pass the second object in by reference or whatever. Advice?

I can think of a couple ways of approaching this, but first maybe you should explain why you need functionality from a different object to destroy your object?
 
If it is required at time of destruction, pass it in on construction. It it's optional, set it after construction. If this makes construction complicated and you need to construct them often, create a factory to build these things in the configuration you desire.

Another option is to make the function of the helper object static (if this is possible). I guess we need clarification on what this other object does, and what the destructor wants to use it for.
 

The Technomancer

card-carrying scientician
If it is required at time of destruction, pass it in on construction. It it's optional, set it after construction. If this makes construction complicated and you need to construct them often, create a factory to build these things in the configuration you desire.

Hm, not quite sure what you're saying. Here's what I have
Constructor:
Code:
PlayerObject::PlayerObject(b2World* World, int xpos, int ypos){
	//stuff
	Body = World->CreateBody(&BodyDef);
	//stuff
}




And I want for the destructor to contain
Code:
PlayerObject::~PlayerObject(){
World->DestroyBody(Body);
}


I can think of a couple ways of approaching this, but first maybe you should explain why you need functionality from a different object to destroy your object?
I'm working with the physics engine Box2D, and I tie Box2Ds physics objects to my more generic game objects. However I suspect that if I just call the destructor on the game object it will leave the physics object behind, so I want my destructor to explicitly destroy the physics object as well.
 

Blizzard

Banned
If you don't have access to World, just make it a member variable, sure. It should be by far the easiest way to handle it as long as World is never going to be deleted or changed while that particular object is active.

You might want to make sure of how Box2D handles deleting stuff though, since it sounds like you are unsure about whether certain of its objects get automatically deleted, and if say, DestroyBody's implementation happens not to do some safety checking internally, you might delete something twice.
 

The Technomancer

card-carrying scientician
Hm, okay. I've got a class that I basically just use to organize a bunch of static functions that I call with some frequency. I thought that by extension I could create a static int that could be used the same way, but I'm getting unresolved external errors whenever I try to compile. Did I fuck up?
 

Slavik81

Member
Hm, okay. I've got a class that I basically just use to organize a bunch of static functions that I call with some frequency. I thought that by extension I could create a static int that could be used the same way, but I'm getting unresolved external errors whenever I try to compile. Did I fuck up?

Static variables in C++ are annoying. You need to put a definition of the static variable in the source file, just like you would with a function.

Code:
// in StaticClassName.cpp
#include <StaticClassName.h>
int StaticClassName::intName = INITIAL_VALUE;
 

The Technomancer

card-carrying scientician
Static variables in C++ are annoying. You need to put a definition of the static variable in the source file, just like you would with a function.

Code:
// in StaticClassName.cpp
#include <StaticClassName.h>
int StaticClassName::intName = INITIAL_VALUE;

Well at least its a fairly easy fix, thanks.
 
Making the world a member of the object is not the ideal solution IMO, because it increases the size of each instance of an object by the size of a pointer. If your world has tens of thousands of objects, this can actually start to become significant.

Most actual games use lots of "manager" classes. These are classes with static members that basically return global instances of things. So you could say something like

WorldManager::GetWorld()->RemoveObject(this);
 

Slavik81

Member
It's not ideal, but I wouldn't worry about it unless RAM or cache misses are actually a problem. In a hobby project, it's easy to get caught up on perfecting unimportant details.

I'm also pretty sceptical about the use of singletons, but I do come from a background of application development, rather than game development. My adherence to dependency injection is pretty stringent, and I would almost certainly use a factory from which game objects can be created or returned to instead. It could hold a single reference to each thing that any game object may need to register with.
 
It's not ideal, but I wouldn't worry about it unless RAM or cache misses are actually a problem. In a hobby project, it's easy to get caught up on perfecting unimportant details.

I'm also pretty sceptical about the use of singletons, but I do come from a background of application development, rather than game development. My adherence to dependency injection is pretty stringent, and I would almost certainly use a factory from which game objects can be created or returned to instead. It could hold a single reference to each thing that any game object may need to register with.

It's not actually inherently a singleton though, because you still have the ability to create multiple instances. It's just that your manager class only contains 1 of those instances. So it's a bit different, more flexible if you will.

It also greatly simplifies your code, because you don't have to be passing this world object to every single thing you ever create. The only thing really "bad" about it is that it acts like a "global", which everyone is always taught is "bad".
 
This is C and not C++ but I didn't find a C Programming Help thread so bear with me.

I'm in an intro to programming class and I'm trying to work my way through the chapter review problems in preparation for my test next week...and I don't understand...anything. I don't even think I know enough to ask the right questions. Nevertheless...

The problem is to write a program that sums the numbers 1 through 10, prints the sum, and calculates and prints the average.

I tried using a for loop, but I have no idea what I'm doing. This is the clumsy code I have right now. I don't have a C compiler on my computer and have to wait to get into the lab tomorrow but I was hoping for some help on the problem before then.

Code:
#include<stdio.h>
int main ()

{

int a, b, c, d, e, f, g, h, i , j;

a = 1
b = 2
c = 3
d = 4
e = 5
f = 6
g = 7
h = 8
i = 9
j = 10

      sum = a+b+c+d+e+f+g+h+i
     
      printf(&#8220;The Sum of the integers 1 through 10 is %d/n&#8221;, sum);

      avg = (float)sum/10.0;

      printf(&#8220;The Average is %d/n&#8221;, avg);

      return 0;
}

and my attempt at solving using a for loop

Code:
#include<stdio.h>
int main ()
{
       int i;
       int sum;
       sum = 0;
       
       for ( i = 0; i <= 10; i++)
       {
             sum = sum + i;
        }

printf(&#8220;Sum of the intergers 1 through 10 is %d/n&#8221;, sum);

avg = (float)sum/10.0;

printf(&#8220;The average is %d/n&#8221;, avg&#8221;);

return 0;
}
 
You need to create a variable to hold the sum of the numbers outside the for loop. Then inside the for loop you want to add the sum of the preceding values to the next value it adds.

So 0+1 = 1: 1+2 = 3: 3 + 3 =6 and so on.

First time actually in here helping instead of asking for help, so I hope I explained it well enough.
 
I think I got the first part, but I'm still not sure what should be the "statement" within the for loop to tally the numbers as it goes through the loop.
 

Slavik81

Member
Always initialize your variables when you declare them. Otherwise, they could start with any value.

What makes C++ better than C#?
It depends, but C# is compiled on the fly (just-in-time compiling). This generally makes it slower than executing pre-compiled code, but it has a number of advantages. One is that because it only compiles to machine code at the time of execution, it can make optimizations based on things that are only known at run time.

I think I got the first part, but I'm still not sure what should be the "statement" within the for loop to tally the numbers as it goes through the loop.
Your loop is fine as it is. You just need to initialize your sum so it has a defined value when you start adding to it in the loop.
 

loosus

Banned
Always initialize your variables when you declare them. Otherwise, they could start with any value.

Is this still true? I was under the impression that all modern compilers stuck "0" as the default if it's uninitialized...but shit, I don't even know where I read that, so I could be way off.
 
What makes C++ better than C#?

The fact that it compiles to assembly and doesnt have a virtual machine translation layer?

I mean obviously im not using "better" in the universal sense, but this a necessary property for developing certain types of applications.

Also not having garbage collection is necessary for semi real time apps. I dont think you can ever find a c# game that runs at 60fps because if you do the math thats only 17ms per frame. Garbage collection starts to become pretty significant at that point and can cause very serious stuttering
 

Slavik81

Member
Is this still true? I was under the impression that all modern compilers stuck "0" as the default if it's uninitialized...but shit, I don't even know where I read that, so I could be way off.

That's true of Java and a lot of newer languages. It's not true of C or C++. The language committees avoid making any choices for the programmer that might have negative performance implications. This is partly why C++ is so hard to use properly.
 

Feep

Banned
Also not having garbage collection is necessary for semi real time apps. I dont think you can ever find a c# game that runs at 60fps because if you do the math thats only 17ms per frame. Garbage collection starts to become pretty significant at that point and can cause very serious stuttering
The fuck?
 

The Technomancer

card-carrying scientician
Is this still true? I was under the impression that all modern compilers stuck "0" as the default if it's uninitialized...but shit, I don't even know where I read that, so I could be way off.

Nope, in C++ it still defaults to whatever value happens to be in that memory location unless you specify otherwise.
 
The fuck?

Which part do you dispute? My first claim may have been a little strong about NEVER being able to find a 60 fps c# game, but id be surprised if it were a non trivial game. Happy to have you prove me wrong though.

Or were you talking about one of my other 2 points?
 

Feep

Banned
Which part do you dispute? My first claim may have been a little strong about NEVER being able to find a 60 fps c# game, but id be surprised if it were a non trivial game. Happy to have you prove me wrong though.

Or were you talking about one of my other 2 points?
Not that Sequence is a particularly graphically complex game, but I was measuring an average of only 3.54 ms per frame on most points.

Here are much more complex games, coded in C# and XNA, all 60 FPS to my knowledge:
Hacotama
Prismatic Solid
Dust: An Elysian Tail
TIC: Part 1
Orbitron: Revolution

These are all made by extremely small/single person indie teams, running on the Xbox 360's 2004/2005 technologies. There are also very impressive C# engines out there (Sunburn in particular), though you don't see a lot of studios use them, since they require a great many more assets than an indie studio is generally able to produce.

Garbage collection isn't that big a deal, generally. Obviously you'd use C++ for maximum performance, but we're WAY past the point of C# not being able to handle some impressive stuff, even at 60 FPS.
 

RiZ III

Member
Is this still true? I was under the impression that all modern compilers stuck "0" as the default if it's uninitialized...but shit, I don't even know where I read that, so I could be way off.

Only variables declared at global scope. Or static variables.
 
Garbage collection isn't that big a deal, generally. Obviously you'd use C++ for maximum performance, but we're WAY past the point of C# not being able to handle some impressive stuff, even at 60 FPS.

the problem isnt that the amount of time a single collection takes is large, it's that due to the non deterministic nature of the GC, it can be very erratic. If a single 3ms collection comes in you'll get an instant 10fps drop, and those kind of numbers are well within the realm of possibility for a garbage collection. It doesnt have to be frequent to be noticeable.

But I guess im used to developing larger games with more severe memory pressure.

Many of the games on that list im not familiar with, but ill check them out
 

wolfmat

Confirmed Asshole
Also not having garbage collection is necessary for semi real time apps.

This is obviously not true. In the first place, garbage collection performance depends on the amount and longevity of objects. If your 3 objects never die, then garbage collection does nothing at all.

Just keep away from manual operations in garbage collection and keep the object-orientedness sane. You'll be okay.
 

Feep

Banned
the problem isnt that the amount of time a single collection takes is large, it's that due to the non deterministic nature of the GC, it can be very erratic. If a single 3ms collection comes in you'll get an instant 10fps drop, and those kind of numbers are well within the realm of possibility for a garbage collection. It doesnt have to be frequent to be noticeable.

But I guess im used to developing larger games with more severe memory pressure.

Many of the games on that list im not familiar with, but ill check them out
There are numerous techniques to reduce garbage collection footprints, including not needing garbage collection by not allocating reference type objects all the time. Many of the high performance Xbox LIVE titles as well as some of the more intense independent titles on Windows Phone do this to maintain performance and avoid garbage collections.

In addition, if your game isn't hitting that 16.66 ms limit, even a 3ms GC wouldn't affect anything. Mine wasn't even close.
 
This is obviously not true. In the first place, garbage collection performance depends on the amount and longevity of objects. If your 3 objects never die, then garbage collection does nothing at all.

There exist some semi real time garbage collectors, but they are pretty specialized, so in the general case, it is true. Unless you're using an unorthodox definition of real time.
 

wolfmat

Confirmed Asshole
There exist some semi real time garbage collectors, but they are pretty specialized, so in the general case, it is true. Unless you're using an unorthodox definition of real time.

I've got some experience with coding realtime applications in Java, a language where you really can't escape the garbage collector, and I can say that I've thoroughly tested for garbage collection problems numerous times in diverse scenarios and saw no principal flaws whatsoever. And I'm not a genius with these under-the-hood things. I just keep my structures sane. I use OO where it makes a difference.

Don't OO-ify your vertices, polys, bezier handles and so forth. Don't do dumb stuff. All you want to do with those is have them ready, so just dump them into everlasting structures, and flush when you need to (loading&#8230;). As long as you're aware that objects in realtime applications are supposed to fulfill grand-stroke needs, you're doing it right. If all you want to do is inherit and inherit, you're doing it wrong.

Here's a simple scenario: You have a tree of 3D meshes that inherit rotation and location upwards.
Make an object "Mesh", dump imported geometric data into native arrays, feed that to the GPU (maybe as vertex lists or VBOs), operate on OGL addresses. Do rotation and location with stacked matrices. If your data is dynamic beyond whole-mesh rotations, like with skeletal per-vertex skinning or whatever, write shaders so that the bulk of these operations is on the GPU (where you really want it).
Don't give each vertex, poly, UV segment and so forth an object. That'll break your neck when it comes to garbage collection.

You would do exactly the same with C++.

Here's a tougher scenario: Dynamically-defined changing UI defines procedurally-generated datasets (like, you can add a new textfield with the caption "Text", and when you enter text, it is displayed in 3D in the main view).
Make the UI OO through and through, but follow the IMGUI concept (look it up, it generally just makes sense in realtime scenarios). Have generic datasets as manipulation templates (in the above example, 3D letter sets make sense), keep UI-derived dynamic data in non-OO structures like arrays, operate on array fields directly in your UI event handlers via one hash table. Don't look for dynamic data in the buttons when you render; look in the array and feed array data to a shader.
Therefore, buttons may die, but the data never dies. You won't have 10M buttons, but you will have 10M data fields. You've saved garbage collection a lot of work!

Another scenario: Music playback. Like, Ogg Vorbis. With chunks to throw at OpenAL. You can't give each chunk an object. Obviously. You're gonna murder the stack and drown the garbage collector for no reason. So don't do it.

The essence is: "If you have masses of dynamic data points in a realtime application, don't throw OO at 'em."

Edit: Caveat: Some scenarios are not well-suited for OOP, so it's important to evaluate on that level in the first place.
 

maharg

idspispopd
The things you're saying "you'd do exactly the same in C++" aren't really true for one simple reason: Every object in C++ can be allocated exactly how and where you'd like to. There's no artificial division between stack objects and heap objects with different characteristics. You don't need to avoid inheritance or even virtual functions just to avoid garbage collector pauses, and you can manage memory on your own terms, with deterministic behaviour in terms of freeing resources -- even in critical paths.

Look, I'm a fan of several languages that quite simply would not exist without GC, but trying to pretend that the contortions Java and .net programmers go through to avoid GC pauses are anything like programming in a deterministic environment is just plain wrong.
 
The things you're saying "you'd do exactly the same in C++" aren't really true for one simple reason: Every object in C++ can be allocated exactly how and where you'd like to. There's no artificial division between stack objects and heap objects with different characteristics. You don't need to avoid inheritance or even virtual functions just to avoid garbage collector pauses, and you can manage memory on your own terms, with deterministic behaviour in terms of freeing resources -- even in critical paths.

Look, I'm a fan of several languages that quite simply would not exist without GC, but trying to pretend that the contortions Java and .net programmers go through to avoid GC pauses are anything like programming in a deterministic environment is just plain wrong.

yea, this. I mean, "real time" and "non-deterministic" are basically incompatible properties, and this is literally by definition.

yes, there are garbage collectors that guarantee worst-case scenario performance, and hence guarantee determinism, but neither Java's, C#'s, nor any other one in mainstream usage has this property as far as I know.

I'm not saying garbage collection sucks, only that it is incompatible with real time applications. And for the same reason, it is very often incompatible with semi-real time applications as well

TL;DR - I was probably wrong to originally speak in absolutes. But nevertheless, I still think the point stands.
 

Feep

Banned
TL;DR - I was probably wrong to originally speak in absolutes. But nevertheless, I still think the point stands.
It does not stand, because while GC is a significant obstacle in more technically advanced real-time applications, it can be overcome using a variety of methods and easily allows for modern looking games running at 60 FPS. It's not even hard. Seriously.
 

wolfmat

Confirmed Asshole
The things you're saying "you'd do exactly the same in C++" aren't really true for one simple reason: Every object in C++ can be allocated exactly how and where you'd like to. There's no artificial division between stack objects and heap objects with different characteristics. You don't need to avoid inheritance or even virtual functions just to avoid garbage collector pauses, and you can manage memory on your own terms, with deterministic behaviour in terms of freeing resources -- even in critical paths.
Yeah, I didn't think that through, just threw it out there. Let me rephrase: You'd do something along those lines in C++ anyway, albeit for other reasons. Reducing cache misses, boilerplate code and the like.

Look, I'm a fan of several languages that quite simply would not exist without GC, but trying to pretend that the contortions Java and .net programmers go through to avoid GC pauses are anything like programming in a deterministic environment is just plain wrong.
My position is that you have to weigh pros and cons. Does the performance hit of garbage collection affect Hz? Do you need to manage memory minutially? How much is in objects, what is your general inheritance framework idea? What lifecycles are to be expected? What will be the memory layout? Data pathways? You want to always think about these things anyway.

So think about them, and choose the appropriate language. Your planned application being realtime is not a dealbreaker for garbage-collecting languages all by itself, so if it's justified, go ahead and benefit from garbage collection conveniences if you can.

Literally speaking, so you start out with C#. The consequences: Your Tetris clone will be okay. Your word puzzling game will be okay. Your 3D open-world MMO with mining and crafting probably won't be unless you jump through some hoops (s.a.). Your non-linear video editing tool will never get to a point where realtime user-defined graph-driven filter previews are feasible unless you're a genius of some sort.

So is the life of a programmer. Pick your battles wisely.
 

maharg

idspispopd
yes, there are garbage collectors that guarantee worst-case scenario performance, and hence guarantee determinism, but neither Java's, C#'s, nor any other one in mainstream usage has this property as far as I know.

Lua has relatively recently switched to an incremental collector with controlled pause times (where if the pause isn't long enough the garbage will pile up). This is almost certainly because one of its primary purposes at this point is as a game engine scripting language.
 
It does not stand, because while GC is a significant obstacle in more technically advanced real-time applications, it can be overcome using a variety of methods and easily allows for modern looking games running at 60 FPS. It's not even hard. Seriously.

I guess we're just going to have to agree to disagree. You may be able to get away with it for simpler games, but I just don't see it happening on larger games, many of which are already struggling to push 60fps even in a deterministic environment. Try having a game with thousands, or tens of thousands of objects in your world and then telling me that you can get around garbage collection. Even if you come up with some crazy pooling scheme and/or manual allocation scheme on top of the GC, then all you're actually doing is defeating GC, which case I'd argue that you aren't actually using GC.

In an environment with heavy memory pressure, which really let's be honest with ourselves, is pretty common in game development, it just isn't going to happen.

Otherwise, why are a majority of large games still written in C++? Because the devs are "stuck in the past"? Come on.
 

Feep

Banned
I guess we're just going to have to agree to disagree. You may be able to get away with it for simpler games, but I just don't see it happening on larger games, many of which are already struggling to push 60fps even in a deterministic environment. Try having a game with thousands, or tens of thousands of objects in your world and then telling me that you can get around garbage collection. Even if you come up with some crazy pooling scheme and/or manual allocation scheme on top of the GC, then all you're actually doing is defeating GC, which case I'd argue that you aren't actually using GC.

In an environment with heavy memory pressure, which really let's be honest with ourselves, is pretty common in game development, it just isn't going to happen.

Otherwise, why are a majority of large games still written in C++? Because the devs are "stuck in the past"? Come on.
Because C++ is better for high performance applications than C#. Obviously.

Prismatic Solid in particular has tens of thousands of objects rendered on screen at certain points, once again, running on 2004 technology and coded by a single guy.

And you said games couldn't be made 60 FPS in C#. If you bypass/avoid the GC, you're still using C#.

It's slightly annoying to me because games don't need to be pushing the bleeding edge of graphical prowess to be fun. I coded a game in C# that was relatively well-received in the marketplace (at 60 FPS, without a hitch, I might add), and I'm not sure if I could have done it without the obvious benefits conferred to me by C# and XNA. By saying "you can't make games in C#", you discourage programmers from going out and making a fun game using an excellent toolset. Yes, you can make games with C#, and yes, you can make games that deal with garbage collection.
 
In an environment with heavy memory pressure, which really let's be honest with ourselves, is pretty common in game development, it just isn't going to happen.
FWIW the memory pressure in modern console games has little to do with per entity cost; the lion's share of physical memory is spent on rendering related assets and buffers, there hasn't been nearly as significant growth in general heaps related to simulation/behaviors, etc. It's not uncommon today to have 30MB of render targets, e.g, the entire physical memory from the PS2 era.
 

wolfmat

Confirmed Asshole
Otherwise, why are a majority of large games still written in C++? Because the devs are "stuck in the past"? Come on.
Exactly. They're using C++ because it makes sense. And because they are experienced programmers through the bank, so they've got multiple approaches for dealing with memory ready.
But you can't use the ideal professional approach of the most experienced programmers in the field to making large games as a model for everything realtime. And you don't have to. That's what I'm harping on about. You want to code to harvest your strengths, and to cater to your game concept. If you're good either way, then pick the easier route.

As an aside, history shows that manual memory management makes programmers (even the stars) run into swords left and right. As long as you can avoid that without much of a hit, you want to.
 
So this seems the best place to ask, are there any good online guides or books for absolute beginners to C++? It's something I'm interested in but just want to test the water because I'm really not sure I'm smart enough to learn it. And looking through this thread, I might be right :p
 

Slavik81

Member
Are you a beginner to programming in general?

If you know your way around other languages, Effective C++ by Scott Meyers covers a lot of the gotchas. When you're trying to figure out how things work, you'll probably discover the C++ FAQ, and likely the FQA as well.
 

The Technomancer

card-carrying scientician
So this seems the best place to ask, are there any good online guides or books for absolute beginners to C++? It's something I'm interested in but just want to test the water because I'm really not sure I'm smart enough to learn it. And looking through this thread, I might be right :p

Check your library for a copy of C++ Primer. It basically taught me programming from almost complete scratch
 

The Technomancer

card-carrying scientician
Damn, my first recursive include problem. I have two header files, each of which needs access to the other, and I'm wracking my brain trying to figure out what I can modify.
 
Status
Not open for further replies.
Top Bottom