PDA

View Full Version : C++ and Classes



drakaza
09-14-2000, 02:28 AM
Hello everyone...

I have been C coding for a few years now, and have not gone to C++ because I heard that it is not easily "portable"...

Now that I think of it, why wouldn't it be? I thought you could use C++ with linux

What I am asking is if anyone can list any advantages and/or disadvantages of using C++ for an OpenGL based engine...and what the "portability" capabilities are...

Thanks for your time,
Drak

NewROmancer
09-14-2000, 04:09 AM
Sir I'm sorry but I really don't understand your question. Are there in the world programmers that code in pure C? I learned about them in the history books. They said that they were good but they don't exist today. Why? Because today programming is Object orientated and C isn't object orientated (but somehow you could emulate some classes with struct). The main difference between the C and C++ is the ++,-- operators, the appearance of keyword class, I think that the virtaul tables of the classes, operator overridng and overloading aso


NewROmancer

drakaza
09-14-2000, 05:42 AM
Thanks for replying!

Well, for example...ignoring the fact that there was some assembly code in it, Quake was written in just C, and i imagine Quake2 was too.

What I want to know is if C++ programs can be "ported" to other platforms easily (e.g. linux). Some people say no..and I want to learn why! because "object-orientism" seems the way to go for really clean code!

Thanks!

MikeC
09-14-2000, 05:57 AM
Originally posted by NewROmancer:
Sir I'm sorry but I really don't understand your question. Are there in the world programmers that code in pure C? I learned about them in the history books. They said that they were good but they don't exist today. Why? Because today programming is Object orientated and C isn't object orientated (but somehow you could emulate some classes with struct). The main difference between the C and C++ is the ++,-- operators, the appearance of keyword class, I think that the virtaul tables of the classes, operator overridng and overloading aso


Huh???

Yes, there are quite a few programmers still writing pure C, though usually for systems software rather than apps. OO is wonderful for a great many things, but it's not a silver bullet. (Which is why Stroustrup describes C++ as a "multiparadigm" language rather than an OO one.) Almost every benefit of moving to C++ has an associated downside. Dynamic binding means sacrificing a lot of static validation. STL collections and algorithms mean sacrificing useful compiler errors. Abstracting away from the machine makes it harder to achieve optimal performance (not impossible by any means, but harder).

And yes, there are still some portability issues with C++. The core features should compile just about anywhere these days, but some of the more abstruse features (member templates, Koenig lookup etc) are patchily supported. MSVC isn't too hot on standards compliance, and I suspect they aren't going to do much to rectify the situation.

Re your list of differences... ++ and -- are in C as well. Maybe you're thinking of the use of >> and << for stream IO, which is just an application of operator overloading, not a language feature in itself. The real big differences are:

- classes
- virtual functions
- templates
- exceptions
- overloading

To answer the original question; yes, I think switching from C to C++ is a net win for application-level programming. But be prepared to put a fair bit of effort into learning it before you see the benefits. I like C++ a lot, and use it pretty much exclusively, but it's NOT easy, and you can get yourself into a world of trouble if you don't know what you're doing. If you're comfortable with C, as it sounds, expect to see a drop in productivity before you see a gain.

MikeC
09-14-2000, 06:03 AM
Followup to drakaza's reply... most of the portability issues are history now. If you look at the Mozilla coding standards from a year or so back, they're fairly scary - don't use templates, don't use exceptions, don't use namespaces etc etc. But things have improved to the point where you can write XP C++ and be pretty confident it'll work. Basically, if it builds on gcc and MSVC you should be OK bar the odd tweak here and there.

Oh, and Carmack has said he'll start using C++ in his next game.

ceenda
09-14-2000, 06:33 AM
If I recall correctly, someone from Bullfrog said in an interview that the company was beginning to prefer C++ over C.

drakaza
09-14-2000, 06:44 AM
Thanks Heaps MikeC, that is exactly what i was after...

I actually DID know C++ but never bothered to program with it because i was trying to learn C first... I actually understood it better than C

Now that i am studying JAVA at university, I have a feel for OO, and I see that the cleanness of OO-tism just seems to override any downsides that I can currently see..

so basically the only thing that has to be "ported" is the OS specific code, right?

Thanks very much!

MikeC
09-14-2000, 08:07 AM
No prob. :-)

If you're going from Java to C++, bear in mind that C++ is a much richer language - if you only use the same feature subset that Java does, you'll be missing out in a big way. Templates are the obvious case; less obvious but equally important are inlined concrete classes. (i.e. classes with no virtual functions).

What I always hated about Java was that you kept ending up with a mess of primitives for small-grained data, because Java's everything-is-an-Object straitjacket imposes too much space overhead to make small objects acceptable.

For instance, when I was writing my C++ math lib I kept getting my angle units mixed up. (Math uses radians, OGL uses degrees, animation and modelling often use revolutions.) So I wrote a little Angle class, just wrapping a float, so that all get/set methods made the units explicit, e.g. myangle.radians() or myangle.degrees(). Since then, zero unit errors, without any space overhead. You just wouldn't do that in Java.

drakaza
09-14-2000, 08:23 AM
Yeah, that sounds like a very good idea, because i get my angles mixed up frequently as well

It looks like a long few weeks ahead of me now!

Thanks!

foobar
09-14-2000, 02:12 PM
There is nothing you can do with C++ that you can't do with C. C++ is not a great OO language it is just designed to make things that require a lot of repetitive work in C easier. Generally speaking, using all the features of C++ is not a good idea: just use the bits that make life easier than C.

On the portability side about half of Microsoft C++ is proprietary, so code is not guaranteed to compile on all platforms unless you stick rigidly to standard C++ (I noticed the NVIDIA devkit uses Microsoft specific C++ however!)

[This message has been edited by foobar (edited 09-14-2000).]

grady
09-14-2000, 02:28 PM
Thanks for posting a sensible reply about some of the differences in C++ and Java MikeC. I go to all these linux websites, not because i use linux but because they got lots of forums on those, and i ask what the difference and pros and cons are of the languages that people know, but these worms just get in fights with each other about whose favorite language has the biggest balls, consequently never returning a non-angry answer. personally i only now pascal (LOL) and C++ because thats what they taught at my high school. I try to learn other languages but get majorly discouraged when i can't really see the differences in c++ and say perl ( with the exception of a bunch of built in text finder operators *booooooring* http://www.opengl.org/discussion_boards/ubb/biggrin.gif). anyway, thanks!

MikeC
09-14-2000, 03:20 PM
foobar - yes, and there's nothing you can do in C that you can't do in symbolic assembler, and there's nothing you can do in assembler that you can't do in machine code. So? Making life easier for the programmer is a big deal. In practice a competent coder can do things with a HL OO language that a genius coder couldn't hope to do in asm. Writing a full-featured modern game engine or CAD application in raw hex opcodes may be logically possible, but I'd say it's not humanly possible. It's an important distinction.

I agree that trying to use all of C++ is silly; I've never seen anybody suggest otherwise, least of all the people who designed it. I think you're a little harsh though when you say it's "just" good for automating repetitive C. This is true for vtable dispatching, and partly true for templates, but the thought of trying to implement C++ exception handling in C is enough to give me nightmares. Exceptions are really a whole new programming paradigm.

Not sure what you mean when you say that half of MS C++ is proprietary. AFAIK there's a few extra keywords (some obsolete), a couple of slightly different implicit casting rules, and not much else. My main beefs with MSVC are 1) the fact that it's still not 100% ANSI compliant, and 2) the fact you can't #include the Win32 API header or use the STL without enabling the aforementioned proprietary extensions. Windows I can understand, but not being able to compile the ANSI standard library in ANSI standard mode is contemptible.

grady - yeah, I've seen flamefests like that. It's usually the old horses-for-courses syndrome. Talk to someone doing enterprise server-side programming: C is ancient history, C++ is dead and Java is the Second Coming. Talk to someone doing systems work: asm is reasonable at times, C is the norm and C++ is still too big, too far from the metal and not portable enough. (Java, what's that?) If you do oodles of text processing you couldn't live without Perl; if you don't you can't understand why anyone would touch Perl with a bargepole. This being an OpenGL board, you'll probably get mostly pro-C++ sentiment since it's the best fit for the kind of thing most of us do.

(Having dissed Java already, I should confess to severe envy of its dynamic class loading features. C++ kind of sucks in this area, which makes plugin-based architectures more of a pain than they ought to be.)

Sheesh, I'm waffly tonight. Getting verbose in my old age http://www.opengl.org/discussion_boards/ubb/smile.gif

Shutting up now...


[This message has been edited by MikeC (edited 09-14-2000).]

drakaza
09-14-2000, 05:07 PM
Thanks for the input MikeC

I was just afraid of losing compatibility in the migration from C to C++, but now i don't care, because i prefer cleaner code...

One thing I have noticed with VisualC++ though...i made a tokenizer function and it crashes if i create too many tokenizer structs. There is a problem with the memory allocation (and the debug code points to memory.c [which is part of the windows source code) The thing is..it ONLY crashes if i have the DEBUG libraries linked...but it works fine if the Release libraries are linked...

I can overcome the problem by inserting:

malloc(0);

all alone, at the start of my function

It is damn weird!!

NewROmancer
09-14-2000, 09:49 PM
Ok! It seems to me that here all the guys just flamed like little kids. C is very good but C++ is better. The OO programming is good for games. Let me explain why. Here a few weeks ago was a huge topic of Schlornenburg (Sorry if I mispelled your name) about how can he select a ship in his game. The whole problem was because his program I think it isn't OO. If you want to make a game first you make an abstract class CRealWorldObject from what you derive two abstract classes CRealWorldObjectStatic and CrealWorldObjectDinamic also virtual classes. From CRealWorldObjectStatic you derived the classes for the buildings, trees aso and in the other class you derive the classes for your personages of the game and NPCs. Do this in pure C and you will see that is hell on earth. Doing this class ierarchy makes the logic of the game a lot easier and you can use the polimorphism , late-bindingcode reutilization,virtual functions aso things that will make your work a lot easier and will greatly reduce the time for coding.

This is it all!
NewROmancer

MikeC
09-15-2000, 03:05 AM
Who's flaming? I thought everyone was being remarkably civilized for a language advocacy thread http://www.opengl.org/discussion_boards/ubb/wink.gif

drakaza
09-15-2000, 03:40 AM
Does anyone know much about the C-sharp language that is worth looking into?
Or is it just simply a little bit easier to use and more flexible than C* (wildcard)

MikeC
09-15-2000, 03:57 AM
To everyone outside Microsoft PR, C# looks like a cross between C++ and Java. It has a couple of interesting features compared to C++ (GC and a better component model) but it will be Microsoft-only, regardless of what the PR says, so don't even think about it if portability is a concern.

drakaza
09-15-2000, 04:14 AM
Thanks MikeC,

It looks like I won't touch C-sharp with a 10-foot stick if I could help it!

Damn it, they have the non-portable DX, now a whole language that is MS only? JEEZ!

They might as well buy a chunk of the planet

drakaza
09-15-2000, 04:16 AM
That is, if they have not already...

09-16-2000, 07:09 AM
I've found that you have to have a fairly
low-level technical knowledge of how C++ is
implemented to avoid shooting yourself in
the foot, performance-wise. Luckily, I have
acquired that knowledge :-) Looking at the
assembly generated by different compilers is
quite educational; you should try it.

If you know C, there is no specific reason
to go to C++, other than for educational
purposes.

If you already know C++ and are familiar in
it, by all means use it. It's as portable as
C these days. Just make sure to not overuse
virtual functions, virtual inheritance, RTTI
or exceptions, as these ARE slower than
"plain" code. Use virtual functions where
you would use a function pointer in C, and
you'll do fine.

Especially exceptions are VERY expensive.
Typical implementations are called "zero
overhead" because they don't incur any
overhead when you declare them -- but if you
throw an exception, the runtime will
typically load exception resolution tables
from disk, and walk the stack referencing
these tables, so actually resolving the
throw may be 1000 times more expensive than
a goto!

drakaza
09-16-2000, 04:22 PM
Hmm.. that is quite interesting...

so it would be better to use exception handling if you are initializing something at the very start of a program, or a user-define option change, rather than doing it every frame?

By the way, how compatible is C# with C & C++? I mean just library wise...do you have to get special rebuilt libraries just for C# (e.g opengl32.lib) ?

[This message has been edited by drakaza (edited 09-16-2000).]

09-16-2000, 08:23 PM
Umm... you didn't get the point.

Don't use exception handling for normal flow
control AT ALL. Use exception handling only
for errors. Assume that each thrown
exception takes a full second. That's not
true, but it's a good assumption.

Can C# call system DLLs? I hope so, but as
I haven't seen or used it, I wouldn't know.

drakaza
09-16-2000, 10:45 PM
Thanks bgl, it's much clearer now. I've got some more reading to do on error handling.

Also i thank everyone else too, for all your input! Enough from me.

MikeC
09-18-2000, 03:46 AM
bgl - could you recommend any good sources for learning x86 assembly? I've not written any asm since 68k back on the 'Miggy, but I keep meaning to.

I don't agree that virtual functions should _only_ be used to replace function pointers. A more common scenario is using them to replace a big conditional mess of different calls switched on a type code, which is also very worthwhile.

And sadly C++ is NOT "as portable as C these days". It's close, but it's not there yet.

Rob The Bloke
09-18-2000, 10:37 AM
From what I gather, C# is a rehash of Java++

foobar
09-18-2000, 12:50 PM
glBegin( GL_FLAME );

When I say about half of MS C++ is propreitary I mean: about half of MS C++ is proprietary!! If you look at the documentation it goes someting like

blah
blah
blah
blah
BEGIN MICROSOFT SPECIFIC
blah
blah
blah
END MICROSOFT SPECIFIC

Stuff like extra keywords for compiler hints, anonymous structures, crap type checking, errors as warnings etc...

I only have VC6 but larger MS version numbers usually mean more ****e in a larger space http://www.opengl.org/discussion_boards/ubb/smile.gif

glEnd();

drakaza
09-18-2000, 08:38 PM
Well, when a company is worth $220 Billion, why not go further and create a little world for your company which will later replace all the other worlds out there?

09-19-2000, 06:09 PM
bgl - could you recommend any good sources
for learning x86 assembly?


Sadly, no. I just disassemble and read. And
when there's something really weird (like,
I time an integer multiply to take
FOREVER !?) I go ask the pros around here.

(the 16-clock multiply is 32bit*32bit on
Cyrix hardware, btw).



And sadly C++ is NOT "as portable as C
these days". It's close, but it's not there yet.


Luckily, my code doesn't have to run on
PDP-11s nor on NEC mainframes.

Windows, Linux, BeOS, MacOS and the modern
consoles all have good C++ compilers. So as
long as you don't use compiler-specific
extensions, you should be all set.

And making your code go through MSVC++,
CodeWarrior and GCC with full warnings on
all is a pretty good cleaner-upper; usually
well worth the trouble.

NewROmancer
09-19-2000, 09:43 PM
Here I don't want to begin a war between coding in C++ and C or Assembler but C++ is better than C because of objects (Comment: it is better if your way of thinking is OO, if you think procedural there is no need to learn C++ if you know C). A simple example is MFC. If you use MFC you simplify your like by 90% and MFC is C++. I made programs both in MFC and SDK and I know what I'm talking.
And I don't think I need to learn Assembler (I know the basics - I had a course at school) because it takes to much time to write code in it for simple things.

NewROmancer

Eric
09-19-2000, 09:54 PM
NewROmancer,

Bad idea to talk about MFC : most people who are using OpenGL hate it !

Anyway, I agree with you : when you understand what you are doing with MFC, it saves you a LOT of time !!! Of course, it's useless for games...

Best Regards.

Eric

MikeC
09-20-2000, 01:37 AM
Originally posted by bgl:
Windows, Linux, BeOS, MacOS and the modern
consoles all have good C++ compilers. So as
long as you don't use compiler-specific
extensions, you should be all set.


"Good", yes. "Fully compliant", no. On MSVC6 I've already been bitten by "Koenig lookup only works for operators" and "member templates only work if inlined in the class declaration". There are others; see MSKB article Q243451 for the known list. You might say these are obscure features, but they are part of the standard and they're part of the standard because every so often they're damn useful. The portability issue is not just about proprietary extensions.



And making your code go through MSVC++,
CodeWarrior and GCC with full warnings on
all is a pretty good cleaner-upper; usually
well worth the trouble.

Agree 100%. (In theory; in practice I never seem to get around to it http://www.opengl.org/discussion_boards/ubb/frown.gif You're a better programmer than I am, Gunga Din.)

NewROmancer
09-20-2000, 01:37 AM
If not MFC then OWL, it doesn't matter. The idea is that OO saves you a lot of time and if you know well the compiler you don't have drawbacks in the performance.
Anyway hope that this thread will be closed because we will won't ever get to a common point here about this.

NewROmancer

drakaza
09-20-2000, 04:32 AM
I've done a bit more research.

It seems as though if your "game" objects are diverse, yet similar in structure and need a lot of manipulations, classes (from C++) seem to be the logical choice. In my experience, C++ seems to gain an advantage over C the bigger the code is,whereas (for the biggest difference) C seems to rule when creating the small-scale "brute-force" sort of applications that need grunt but are not visually updated every frame (e.g. compilation program) and also games which do not have a relatively complex data structure (because it takes a long time to create "clean",structured code), but need a good speed.

Please correct me where I am wrong, but this is the conclusions that I am forming...I am as always open to suggestions http://www.opengl.org/discussion_boards/ubb/smile.gif

NewROmancer
09-20-2000, 05:07 AM
To drakaza:

you can write code that you can compile with c libc or c++ libs (the same code...).
I work with MSVC 6 (I worked with Borland products a lot also) and if you know how to write code in C++ is as faster as C (personally i think it's optimized for C++ libs). The C++ is better because you write less code and you can structure your program better. And how many try-catch blocks do you use in a game? When you open a file ...

NewROmancer

09-20-2000, 04:12 PM
>On MSVC6 I've already been bitten
>by "Koenig lookup only works for operators"
>and "member templates only work if inlined
>in the class declaration".

Schucks. I guess I've just been lucky :-)

Part of it is that I put C++ in shared
libraries, and thus necessarily have to
restrict my use of templates.

On the subject of "MFC saves you so much
time" -- that's not because it's C++, that's
because someone else wrote and debugged a
whole lot of code that you can just leverage.
You could write a framework in C which saved
the C programmer as much time.

Ergo: know what you're doing. If you're
tempted into doing something you don't know,
resist, OR do it with the clear expectation
that it will be a learning excercise, not a
full-steam-ahead deadline-hitter.

skw|d
09-21-2000, 01:24 AM
drakaza, it seems this thread has blown up.

Your original question was about the portability of C++, and its advantages and disadvantages.

C++ has a final ANSI standard and is portable across platforms. The problem is when you use system specific code. To make your application portable, make all your system specific code in another source file. For example I have system_init() defined in both x_sys.cc and win_sys.cc, the Makefile will select the right module to compile into the main application. In win_sys.cc system_init() will use WGL functions to setup OpenGL rendering on Windows platforms, but in x_sys.cc system_init() will use GLX. The main application calls system_init() without a care.

Another issue is the compiler, some compilers like MSVS will try to get you to use compiler-specific features which will make your source unportable. I suggest you use gcc, and also get the GNU ports of make, sed and grep for Windows. In this environment you can switch platforms safely and have the same files work for any platform that gcc supports (which is about everything).

The major advantages of C++ is the ability to construct large programs with ease. C++ really shows its power when you have thousands of lines of code. But C++ doesn't do anything that you can't do in C nor in ASM for that matter, because it all comes down to machine code. People tend to choose C++ when you are working with a group of people on a large project. C++ is a tad bit slower than C because of the overhead. Then again, if you really need speed you do it in ASM. C++ also does name-mangling on its symbols so that it can do function overloading, this can be a pain to work with sometimes when integrating with C or ASM.

My suggestion is to stick with what you like to work in, there is no disadvantage by working in C over C++. Though if you are working with a team of people, you might find C++ to be a better choice.

Good Luck,
/skw|d

drakaza
09-21-2000, 02:33 AM
Thanks very much for that post, I've learned quite a lot more about C++ since I posted the first message, and now I think I am confident enough to begin experimenting cross-platform!

Yeah, this thread has mutated almost beyond recognition.

Again, thanks ALL!

[END THREAD]

CitiZen X
09-22-2000, 01:36 PM
There are some compatiblity issues with C++ in some of the new syntaxs presented in MSVC and GCC. At least I've examined that some new features (like multiple inheritance) are implemented diffrently. If you go to lokigames.com and look at the source code for the mjpeg player, it is done in some weird use of C++ (its weird to me because I learned C++ OOP before it was a complete standard) and didn't compile in MSVC. And if you look at COM objects in MSVC you see that it handles it diffrently. I'm not sure which is the better way, and which is the hard way, but quite frankly I think they both suck, and don't give me far enough control and give you a head ache in deciding how to use them effeciently. Like for example, when creating an renderer object and rendering data object, should the renderer be aware of how to render all kinds of rendering data, or should the rendering data draw itself using the renderer. I've seen people try to do it both ways, but it does not work right. I've opted to do it totally diffrent then that all together, and it took quite some time and breaking away from common usage of OOP, and creating callbacks (which are not handled easily in C++ OOP, try calling a random function from another object), and let the renderer decide what it can or cannot draw, and require that rendering data meet the requirements, the rendering object itself just takes in a large scene graph and optimizes itself as best as it can for it (An opengl render for example will convert all pictures in a scene graph into its own texturemap data), but then you have issues of interactivity, so you need some forms of callbacks. Other then callbacks, then there is arrays and inheritance, obviously you cannot have an array of objects of diffrent inherited types, unless its a pointer array.

In some ways I've considered coming out with my own language, and simply creating a converter to convert it to C++. The Qt gui library, does something similar, and another program called GOBI (or soemthing) does that for GTK+.

I'd say that C++ OOP is still complicated despite making it *easier on the typing*, it makes it harder on the mind. What they do in with multiple inheritance is cool, but that has its limitations as well, I like COMs usage of Interfaces, but it has problems as well, such as adding interfaces at runtime to an object would be nice as oposed to compile time, instead of inheriting interfaces, simply add it to it during runtime, like plugin/extensions etc etc. In the end you cannot really depend upon using C++'s OOP syntax to much, even if it is easy to do, you will always have to do things that are not text book examples of using C++ OOP. Its easy to over do it, moderation is important.