C++

Miscellaneous Forums/General Discussion/C++

Hey, I'm looking to get my head around C++. Is there any books/pointers/tutorials/whatever you know of?

About me:

I've been programming for about a year and a half, I've programmed in php, a little c++/c (for writing fast routine functions to plug into blitz), HTML, and BB/Blitzmax, I'd consider myself moderate with OOP.

I know C++'s basic syntax, I have a copy of Sams Teach Yourself C+++ in 10 Minutes, and i've read a couple other books about the basics of C++, though some of it is still fuzzy.


What I'd like to learn:

I'm not interested (at the moment) in writing programs for Mac, linux, ect, only win32 applications/games, with that in mind, I want to know the following:

-A good graphics library, and how to use it. I've looked into SDL, it looks good.
-How to create a basic window/application with graphics canvas to draw to (I've seen window creating code, it's hellish,) does a library exist to make that a little easyer?
-Get a good grip on the way C++ works, (points*, OOP, ect.).

Basicly, from my prespective(correct if i'm wrong) learning C++ will basicly open a door for me to learn any other language much more easily(except for assembly and binary of course.)


So there you have it, what are some good sources to learn C++?

Beginners guides, thats the realm you need to be in, and theres a ton of resources across the internet...

A C/C++ Reference book... Swinging your head around standard C++ is a big job in itself, so having something at hand for a quick 'refresh' is a good idea.

Usually, guides for graphics librarys have a simple chapter or two about WinAPI, and generally show you how to knock out a basic skeleton GUI app, so have a quick glance at the contents of any books first. Its actually not too bad after you learn C++.

Good luck! :)

Gooooooooooooooooooooooooooooooooooooooooooogle.

If you're using Visual studio. Have a look at Ivor Horton's Beginning Visual studio C++ 2005 (or the latest).

For general C++ Ivor Horton's Beginning ANSI C++ is a must.

The easiest solution around the Windows programming, is to use a FrameWork (like MFC for C++ die hards or .NET for the wusses. These are part of the Visual Studio).

If you're not using a MS compiler then the alternative is to use an open-source framework like wxWidgets (the best), gtk or Qt.

A list of web sites
http://www.cppreference.com/index.html
http://msdn.microsoft.com/en-us/library/d06h2x6e.aspx
http://www.glenmccl.com/index.htm
http://www.wxwidgets.org/
http://blog.outofhanwell.com/2006/05/01/linking-msvc-libraries-with-mingw-projects/
http://www.hitmill.com/programming/cpp/cpp.html
http://www.linuxguruz.com/ebooks/eckel/ (thinking C++ ebook)

And the C++ man himself
http://www.research.att.com/~bs/homepage.html

Don't use any Microsoft related solutions, there are better free software compilers and such.

Visual C++ Express isn't too bad. But I prefer Code::Blocks with MingW.

SDL isn't really a useful graphics library if you ask me. It's much more powerful in combination with OpenGL. Even if you do only want to do 2D, use OpenGL. It will give you realtime scaling, alpha blending and rotation. SDL doesn't have any built-in hardware accelerated features.

C++ OOP features are very neat, including overloading functions and operators. I actually miss that a bit in BlitzMax.
STL and templates are worth to take a look at as well.

Almost 2 years ago I bought a C++ book that basically contained all features of C++. It was a book with 800 pages, covering every feature of C++ (although not everything was very in-depth) and I've fully read it. It was a bit easier for me to pick it up because I've been programming for some years now. Still, it wasn't wasted money and it's a good reference. So my advice is, get a good C++ book and read it :-).

And ehm... Since when is binary considered a language? Assembly is actually the lowest form of programming, since you're writing machine code.



Assembly is actually the lowest form of programming
No its not. There is actually one lower, raw machine code (binary).
At Uni we had to program a traffic light circuit using that to show we understood what was happening at the lowest level, its horrid.
"Assembly language" just replaces the raw machine code instructions with something more human readable eg pop, push, cmp, jne etc...
But you are right in the fact that for all intents and purposes they are the same thing :)

Unless you need C++ for a specific reason, I'd recommend learning something more productive and useful like C# or Java, or if you really want to expand your mind, Lisp, Haskell, or OCaml.

And realistically, learning C++ won't help you learn many languages since all newer languages are using automatic garbage collection, have things like reflection, dynamic typing, etc. C++ is the last bastion of the old-school, and most of us have graduated from that school and their outdated methodology of solving problems.


C++ is the last bastion of the old-school, and most of us have graduated from that school and their outdated methodology of solving problems.



Nonsense... C/C++ will be here for quite sometime, for one, who will maintain the billions of lines of code that are out there now. Passing off C++ has a has-been is just sheer lunacy.

C++ is the last bastion of the old-school, and most of us have graduated from that school and their outdated methodology of solving problems

Thats rubbish. C++ is still the fastest, most powerful middle level language and is still used extensively, especially in games, "everyone"(in the industry) knows it and it is fully portable. Plus if you know c++, moving to other languages should be very intuitive.

Disclaimer: I judge these things not from a game developer's perspective. Writing games is only a part of the things that interest me, and I currently make my income in a large corporate environment, so keep this in mind when you read further.

Basically I agree with what SculptureOfSoul said. C++ only excels at being the worst of all available options and has also already entered the COBOL-phase of languages. Unless you want to write that 'next-generation-killer-3D-engine-that-finishes-off-id-software-and-unreal', (which could be done in the even faster C or Pascal languages, by the way), I can hardly see any use for C++ for --new-- projects.

If you want to learn something useful about developing for Windows, buy Charles Petzold's "Programming Windows". The earlier editions use the C language and focus on the Windows API only (which is a good thing). The most recent version of the book is based upon C#, which quickly has become --the-- language of choice for Windows development.

If I were still interested in Windows, I'd code exclusively in C#.NET and wouldn't bother with anything else. That language and framework are the future for Windows and the industry around it, and that pretty much ends the discussion when we are talking about that platform only.

But since I do not believe that in five to ten years from now Windows and Microsoft will still be the big boys on the block, I'm investing my time elsewhere. So-called scripting languages like Python have only just begun to gain momentum and they are the future of application/software development. Nobody except for maybe some geeks is interested in low-level nitty-gritty stuff; productivity counts and cost reduction and the shortest way from inception to shipping. Languages like C and C++ don't give you that, and Java and C# also fall short in that category - although they are much more developer friendly, they're also too verbose and get in your way too quickly compared to Python or Ruby.

Anyway. Enough language bashing for today. And if you really think that C++ is a good language to learn concepts, remember what Alan Kay said.

But since I do not believe that in five to ten years from now Windows and Microsoft will still be the big boys on the block, I'm investing my time elsewhere.

Wishful thinking. They'll still be the "big boys on the block" is fifteen to twenty years, never mind in five to ten.

Personally, I think that unless you are interested in getting a job using C++, there's little point in using it. C will teach you as much if not more of the low level stuff (depending on how you use it) and I found BlitzMax a nice intro to OOP if you want to go in that direction. I found a lot of introductory books on OOP in C++ read like religious texts and were not particularly useful.

Be wary of SDL. It looks great, but I couldn't get it to work on any compiler that I tried. That, and thefact that the most recent developments on and with it seem to be around 2003.

Agree with Winni. If your target is pure Windows, C# or VB.NET is the way to go. Managed C++ would be an alternative as well but its even harder to get than regular C++ and at some point C# and M C++ will merge anyway, its only a question of time till all old libraries have been moved to M C++ ie .NET and will allow the removal of MC++.

Python and Ruby are nice. Lisp is ideal, if only it had more momentum; especially considering it's average speed is nearly that of C++ and is about 4 to 10 times faster than Java, while having more expressive power than any language out there thanks to its macros (which are nothing like C++.) And if you think you know what object orientation is, without having heard of generic methods and the capability of multiple dispatch, well - let's just say there is a lot more to OO than C++ will show you.

I shouldn't say C++ is pointless.. it's not if you're going into the mainstream games industry. But as far as learning useful concepts for picking up other more modern languages, it's really not the best choice. It's a strange hodge-podge of the worst of statically typed langauges and the worst of dynamic languages, imo.

I'm using GLUT to write C++ programs with graphical interfaces: http://www.opengl.org/resources/libraries/glut/
It's very easy and short to code with, and it runs on all platforms.
For example a simple GLUT program which creates a window and draws a triangle would look like this:
#include "GL/glut.h"

void Render()
{
	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
	glBegin(GL_LINE_LOOP);
	glVertex3f(0,0,0);
	glVertex3f(0,1,0);
	glVertex3f(1,0,0);
	glEnd();
	glutSwapBuffers();
}

int main(int argc, char **argv)
{
	glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGBA);
	glutInitWindowPosition(100,100);
	glutInitWindowSize(640,480);
	glutCreateWindow("Window Title");
	glutDisplayFunc(Render);
	glutMainLoop();
	return 0;
}


Most of you are just giving terrible advice. I'm not sure if you're intentionally trying to hinder this guy's learning what he said he wants to learn, but it certainly seems like it. Between Dreamora and Scuplture's spew and the few of you with close to no idea what you're talking about (Lumooja, Buggy), I'll be amazed if he learns anything.

In order of your questions:

1) You have any number of options, including SDL, Allegro, OpenGL, DirectX, or other libraries that use the last two, including Nebula, OGRE (I recommend avoiding that unless you know damn well what you're doing), Irrlicht, etc. You may be better off with Allegro since you don't even understand pointers.

2) This is pretty much dependent on the platform. In Windows, you'll have to get familiar with its API, under Linux you'll use X, under Mac OS I'm actually not sure. I believe Carbon had something to do with it, but you'd have to ask someone who writes code for Macs.

3a) Read The C++ Programming Language by Bjarne Stroustrup.

3b) Pointers are a confusing thing for me, because I have no idea how they can be confusing for other people. It's not as if they're incredibly complex, so I don't know what it is you're doing to make them so. As such, I think it would be best if you forget everything you think you know about pointers and started from scratch learning them.

3c) So, read the book written by the guy who created the language. Do this before you even bother attempting to do the first two. Doing those as you learn is fine, but not before you learn. That would just be stupid.

@Noel: I don't know what you mean, but my example code works 100%. I tested and ran it before I posted the source. You can do in the same way a whole GUI, and replace explorer.exe with it.

You use GLUT.

GLUT works just fine, and you get the full source code of GLUT too, so you can make your own improvements to it. I haven't needed to change GLUT source yet.

GLUT is strictly for beginners and people who do not know what they are doing. Which would you like to be? Either way, neither sort of person should be giving advice to a beginner as you are.

I don't see how full source code is only for beginners. Beginners and advanced developers can change the source code how they like.

If I was to learn OpenGL in C++, I would go straight for the low-level API, not a lib built on it. Defeats the object really, of learning and that! :)

Thanks for all the replies guys.


Yeah, I intend to learn the low level stuff, but some graphics libs like SDL ect, are nice, because programming graphics libraries looks like horribly advanced stuff. But win32 stuff doesn't look to horrible if you get to know it.

Currently I use this bloodshed dev-C++ IDE/compiler.

I'm not looking into buying a IDE/compiler yet (maybe later after I cover some basics)

This is what the compiler comes with for a standard window creation routine:

#include <windows.h>

/* Declare Windows procedure */
LRESULT CALLBACK WindowProcedure(HWND, UINT, WPARAM, LPARAM);
/* Make the class name into a global variable */
char szClassName[ ] = "WindowsApp";
int WINAPI WinMain(HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, int nFunsterStil)

{
    HWND hwnd;               /* This is the handle for our window */
    MSG messages;            /* Here messages to the application are saved */
    WNDCLASSEX wincl;        /* Data structure for the windowclass */

    /* The Window structure */
    wincl.hInstance = hThisInstance;
    wincl.lpszClassName = szClassName;
    wincl.lpfnWndProc = WindowProcedure;      /* This function is called by windows */
    wincl.style = CS_DBLCLKS;                 /* Catch double-clicks */
    wincl.cbSize = sizeof(WNDCLASSEX);

    /* Use default icon and mouse-pointer */
    wincl.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wincl.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
    wincl.hCursor = LoadCursor(NULL, IDC_ARROW);
    wincl.lpszMenuName = NULL; /* No menu */
    wincl.cbClsExtra = 0;                      /* No extra bytes after the window class */
    wincl.cbWndExtra = 0;                      /* structure or the window instance */
    /* Use light-gray as the background of the window */
    wincl.hbrBackground = (HBRUSH) GetStockObject(LTGRAY_BRUSH);

    /* Register the window class, if fail quit the program */
    if(!RegisterClassEx(&wincl)) return 0;

    /* The class is registered, let's create the program*/
    hwnd = CreateWindowEx(
           0,                   /* Extended possibilites for variation */
           szClassName,         /* Classname */
           "Windows App",         /* Title Text */
           WS_OVERLAPPEDWINDOW, /* default window */
           CW_USEDEFAULT,       /* Windows decides the position */
           CW_USEDEFAULT,       /* where the window ends up on the screen */
           544,                 /* The programs width */
           375,                 /* and height in pixels */
           HWND_DESKTOP,        /* The window is a child-window to desktop */
           NULL,                /* No menu */
           hThisInstance,       /* Program Instance handler */
           NULL                 /* No Window Creation data */
           );

    /* Make the window visible on the screen */
    ShowWindow(hwnd, nFunsterStil);
    /* Run the message loop. It will run until GetMessage( ) returns 0 */
    while(GetMessage(&messages, NULL, 0, 0))
    {
           /* Translate virtual-key messages into character messages */
           TranslateMessage(&messages);
           /* Send message to WindowProcedure */
           DispatchMessage(&messages);
    }

    /* The program return-value is 0 - The value that PostQuitMessage( ) gave */
    return messages.wParam;
}

/* This function is called by the Windows function DispatchMessage( ) */
LRESULT CALLBACK WindowProcedure(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)                  /* handle the messages */
    {
           case WM_DESTROY:
           PostQuitMessage(0);        /* send a WM_QUIT to the message queue */
           break;
           default:                   /* for messages that we don't deal with */
           return DefWindowProc(hwnd, message, wParam, lParam);
    }
    return 0;
}



anyway, what other compilers are there out there? Plus I think this IDE is out of date, so i'm going to look into their website.

But win32 stuff doesn't look to horrible if you get to know it.


Perhaps, but you'll find it won't work very well on MacOS X or Linux.

what other compilers are there out there?


The most popular free compiler (comes with DEVC++ and is a must for BlitzMax) is Mingw. The other are Open-Watcom. Borlands C++ 5.5 and Digital Mars.

For IDE's the best free one so far that I have used is Code::Blocks

Here's a place to look for most things http://www.thefreecountry.com/

anyway, what other compilers are there out there? Plus I think this IDE is out of date, so i'm going to look into their website.

Microsoft Visual Studio 2008 C++ Express is free, and it produces the fastest code on Windows.

Get the NeHe tutorials and Dev C++ that way you can make OpenGL games without the requirement for GLUT. As has already been mentioned GLUT is for beginners but its a good starting point :)

@Buggy
SDL Is still actively being developed. Last update was not in 2003. SDL 1.2.13 was released on 31 December 2007. Latest commercial game using SDL I can remember is Quake Wars: Enemy Territory.

Check out http://www.lazyfoo.net to get started with SDL.

@EdzUp: NeHe tutorials are great, but they are using win32 window creation which is very bad. Of course that does not matter as you can just cut the win32 part out and replace it with GLUT.
If you call GLUT for beginners, I call win32 API for people who haven't learned anything since they were beginners, making them even worse than beginners.

Currently I use this bloodshed dev-C++ IDE/compiler.
Dev-C++ is not a compiler, it is only an IDE. It may come with MinGW.

I don't see how full source code is only for beginners. Beginners and advanced developers can change the source code how they like.
How does having the source code not make you a beginner? Did this make sense to you when you wrote it?

@EdzUp: NeHe tutorials are great, but they are using win32 window creation which is very bad. Of course that does not matter as you can just cut the win32 part out and replace it with GLUT.
If you call GLUT for beginners, I call win32 API for people who haven't learned anything since they were beginners, making them even worse than beginners.
Are you stupid? O_o

@Noel: No, but I think you can not see the whole picture. For example in our company we are starting to upgrade all Windows XPs to Ubuntu, and I saw this coming and started converting all programs to OpenGL/GLUT long time ago. If I hadn't done that, I would be have been quite unprofessional and shortsighted using win32 API only.

I call win32 API for people who haven't learned anything
Erm, you might want to wiki that :P

For example in our company we are starting to upgrade all Windows XPs to Ubuntu
That's not an upgrade, that's a replacement. An upgrade only occurs when you replace one version with a newer version.

For example in our company we are starting to upgrade all Windows XPs to Ubuntu, and I saw this coming and started converting all programs to OpenGL/GLUT long time ago. If I hadn't done that, I would be have been quite unprofessional and shortsighted using win32 API only.
Also, it is not unprofessional and shortsighted to develop for your target platform using that platform's API. Many programmers have this unusual talent for thinking up these vast plans so that they never have to update software. As a result, the software they develop is a huge mess that is never truly adequate and always in need of support.

You should develop using your platform's API where necessary. Your code is less likely to contain bugs in doing so and you're less likely to introduce bugs in the code you wrote to avoid the platform's API.

Thanks for answering my question, although a 'yes' would have sufficed.

Perhaps, but you'll find it won't work very well on MacOS X or Linux.
Or 64-bit versions of Windows - which you'll need in order to utilize that huge amount of memory you'll want.

You should develop using your platform's API where necessary.
I'm fairly sure you mean "available". You should always use the platforms API to do something. For starters like Noel said the API is almost certainly more rigorously tested than your code. More importantly, should you discover a bug and/or design flaw, you can always do the fashionable thing and blame Microsoft.

>Microsoft Visual Studio 2008 C++ Express is free, and it produces the fastest code on Windows.

I don't like VC++, maybe because I didnt give it enough time, but still. Basicly, I had the feeling of no control, I just sat there dragging windows GUI onto a window. And even at that, It didnt turn out right. I guess I just like coding better.

I don't like VC++, maybe because I didnt give it enough time, but still. Basicly, I had the feeling of no control, I just sat there dragging windows GUI onto a window. And even at that, It didnt turn out right. I guess I just like coding better.

You may not have had enough time with it :). I use Visual C++ 2005, and honestly it's the best IDE I've ever used, especially when you consider it's debugging features.

First, remember that when you create a C++ GUI application with the GUI designer in VC++, it's using Managed C++, and I would recommend that you keep as far away from Managed C++ as possible. It's horrible, IMO. C# is a nice language, and so is C++ IMHO, but trying to cross the two into "Managed C++" resulted in a horrible and messed up language.

I use Visual C++ to compile purely native (unmanaged, no .NET) exes from standard C++ code, and what people said earlier is true: VC++ produces the fastest code on Windows, by a very considerable margin over something like GCC. If you want fast code, there's nothing better than VC++.

Another thing, probably the most important thing to me about MS Visual C++ is it's excellent debugger. Believe me, once you use the VC++ debugger to debug a complex part of your program, and you find how easy it is to examine variables and objects, set up watches, and trace a crash through every step of the call stack, I think you'll like it as much as I do :).

..while im not sharing JohnJ enthusiasm about VC++, simply because im not in to it and i dont have any plans to do so, I must push myself away from making up any serious judgement about its purpose, simply because I am not one who knows it..however, based on pure thinking, i have to say that, if VC++ or C++ , is the ONE and ONLY ultimate solution for REAL programming, and forever and ever...I would say that such IT world is poor and has no serious vision in it..since everything is moving, i do belive it will move programming too as well as all this story about one and only ultimate solution for serious 'stuff' such as VC++..

Well if you never use it obviously you'll never know how nice Visual C++'s debugger / other features are. BTW, I don't think anyone's saying that C++ is the language for "Real Programmers" and that it always will be, because of course it's not true. New languages will eventually replace older ones, but for the time being C++ is still the best choice for programming high-performance game engines. That may change, but it's hard to say. C# / Java / etc. are promising languages, but they still need performance improvements before they can compete with C++ for games programming.

Just a word of warning, but learning C++ from books and online tutorials will be very, very frustrating. If your aim is to make a 3D game in C++ then prepare for many years of hard work. OpenGL is actually a great API and once you know a fair bit of C++, will be able to get some cubes and spheres moving about without a problem,(The Win32 API, however, confused the hell out of me.)

The problem starts when you want to load things like textures and models. In Blitz, this can be done with one line of code. In C++ it can take a few hundred lines. Then, if you want to move those models around and interact with them using your mouse, you'll need to learn Algebra which is a task in itself.

Anyway, I think if you're really set on learning on C++, you should enroll in a course where tutors can give you assistance. Just my two cents worth.

If you want programing "Game Engines", C++ is the answer...

If you want programing Games, any "Game Engine" is the answer...

My simple opinion.

Interesting given that NeoEngine and other engines are not using C++ ...

Perhaps on Linux the answer to "Game Engines" is C++ ... but only there luckily.
On Windows C# definitely is an answer as ObjectiveC is on OSX

Perhaps on Linux the answer to "Game Engines" is C++

Dont forget pascal, python, java, blitzmax etc, etc, etc...

Interesting given that NeoEngine and other engines are not using C++ ...

Also interesting that they're slower than C++ engines.

Although if you want to make a simple game that doesn't need top-end graphics, and performance isn't a concern, I think C# would be a perfect language.

C++ is a hard lowish level language, thats why I want to learn it, because later, it will be much easyer to learn other languages.

Besides basic, most other languages have much similar syntax to C++.

Also, i'm having trouble finding a book that properly covers strings, the book i'm reading (Sams teach yourself C++ in 10 minutes) seems to use char arrays, but I know there's a better thing for strings out there (strings.h) correct?

. Believe me, once you use the VC++ debugger
I second this.

String strings work more or less how you would expect them to in Blitzmax. Char arrays is the C way of doing things but people still like to use them. I guess some people are into self-pain.

I don't get why people argue so much about what langauge to learn. Just learn C++ and if you don't like it you can do something else. All this debate doesn't help his original question guys, he wasn't asking what to learn!

Try one of these books:

C++ Primer Plus, 5th edition, Stephen Prata
Object Oriented Programming in C++, 4th edition, Robert Lafore
Accelerated C++, Andrew Koenig

They'll teach you ansi compliant C++ using strings instead of chars, etc.

You can't go wrong with any of these.

True, my mind set is this:

Learn C++ and you'll have a easy time learning other languages (except maybe Assembly and Binary)

Anyways, thanks for all the replies, so far i've got this book to look into:

The C++ Programming Language by Bjarne Stroustrup

Any others? What about a for dummys book? I think i've seen a C++ somewhere. Also there was this book, Sams Teach yourself game programming in 24 hours, or something to that effect, is it any good?

The MS MSDN website is helping alot with creating windows ect. For now i'm learning DOS stuff

I think I got the basic idea of C++ strings:

#include <iostream>
#include <string>
using namespace std;

int main(int argc, char* argv[])
{
    //test
  string str1 = "I'm loving C++";
  string str2 = " .... not";     
  cout << str1+str2 << endl;  
  return 0;


}


The biggest 'Gotcha' i'm getting with the compiler is the stupid ; after each line

Also, i'm having trouble finding a book that properly covers strings, the book i'm reading (Sams teach yourself C++ in 10 minutes) seems to use char arrays, but I know there's a better thing for strings out there (strings.h) correct?

Character arrays are how just about every language internally represents strings, and obviously they're at a lower level than something like BASIC strings. C only supports char array strings, but C++, thanks to operator overloading, allows string libraries to give you very powerful and easy to use string types. The standard C++ string class is std::string, which you can use by #include'ing <string.h> (edit: I see you found it :) ). The advantage to using C style strings (char arrays) though is speed, although the only place I've ever found a real need for this speed is in script compilers (which most people don't do).

As for learning C++, I'd first try learning C, especially if you're not familiar with OOP. Then you can move on to C++ seamlessly and start learning all C++'s nice features one by one, like namespaces, classes, private / public data members, inheritance, polymorphism, etc., etc.

C doesnt fully support OOP though.

And i'm intermediate with OOP, as i've done a few games in OOP with blitzmax...

New question, with blitzmax, how does it represent strings? like would this function return correctly if I were to import it into blitzmax:

string Test(string RetString) {
       return RetString;
}



if I called it in blitzmax like so:

'call C++ function to return a string (test)
local teststr:String = Test("Testing...")
print teststr


I'm going to try that now actually.

oh dang it doesnt work...

No expert, but dont you need to return the array rather than the class?

return RetString.c_str();

Might work :/ ive not tried mixing the two languages yet.

And on the BlitzMax end

String.FromCString(Test(...))

C doesnt fully support OOP though.

Yeah, C is a non-OOP language, so it has no OOP support except I guess you could say structs. But C struct's really isn't object oriented programming, it's just object oriented data.

Yahfree: C++ should be able to return a string just fine. What is the error?

No expert, but dont you need to return array itself, rather than the class?

return RetString.c_str();

No, the string class is totally self contained - if you use C++ strings, then there's absolutely no need to even be aware of the C style, unless of course you need to interface with code that uses C-style strings (which is the purpose of c_str).

Actually, returning RetString.c_str() is very dangerous and would lead to unexpected behavior - if your RetString object was defined locally to the function it's returning from, then after the function returns, RetString will be deleted, and so will it's c_str() value. And due to the way memory is managed, you may still get the proper string value back unless some other variable overwrites it later on, or in another thread.

I get this:

Building test
Compiling:test.cpp
D:/programming/Source/BlitzMax/test.cpp:3: error: `string' does not name a type
Build Error: failed to compile D:/programming/Source/BlitzMax/test.cpp
Process complete




test.cpp:
#include <string>

string Test(string RetString) {
       return RetString;
}


test.bmx:

Import "test.cpp"

Function Test:String(str:String) = "Test"


Local Stringt:String = Test("Testing...")

Print Stringt


bmx file...
Import "string.cpp"

Extern "C"
	Function test$(In$)
EndExtern

Print test("hello")
End


cpp file...
#include <string>
using namespace std;

extern "C" {

	string test(string input) {
		return input;
	}

}


wierd... haven't learned extern stuff yet, will look into it

Yeah, there's no "string" class under global scope - the standard "string" class is under the namespace "std", so you either have to specifically reference it under std ("std::string", rather than "string"), or define "using namespace std;" at the top of the file to assume the std namespace.

As C version:
test.cpp
extern "C"
{
	char* Test(char* RetString)
	{
		return RetString;
	}
}


test.bmx
SuperStrict

Import "test.cpp"

Extern
	Function Test:Byte Ptr(str:Byte Ptr)
EndExtern

Local Stringt:String = String.FromCString(Test("Testing..."))

Print Stringt





As C++ version:
test.cpp
#include <string>

using namespace std;

extern "C"
{
	string Test(string RetString)
	{
		return RetString;
	}
}


test.bmx
SuperStrict

Import "test.cpp"

Extern
	Function Test:String(str:String)
EndExtern

Local Stringt:String = String.FromCString(Test("Testing..."))

Print Stringt


Good to know.

Just as a general hint: forget books that tell you that you learn a massive language like java, C++, C# in X days if X is smaller than 49
You just won't, no mather what you do. You at best get a brief overview which in the end harms more than it helps.

Sad that there are no head first books for C, at least I don't think so. If they are, they are definitely the more or less best resource to learn it. (I've 3 of them and they are great and will teach it in a way that takes care you learned it without beeing dry and useless or usefull at best as a "check back compendium")

You really don't need all that Byte Ptr/FromCString stuff. You can just define c Strings as $z and it gets done for you.

Yes and no (beside $z there is $w as well)

There is one main difference when using above approach: you do not generate trash on each time you call the function. You can manually control when the string is freed which can be of importance when you use that with longer strings for example. BM does not cache them so if you call the function 20 times with the same string it will generate the same temporary c string 20 times, send it and destroy it again.

Returning C strings is potentially dangerous, because C strings are arrays (or pointers to memory), and if the string you're returning is local, it may not be availible after you return from the function, which would result in corrupted data being returned. You either have to make sure any C strings that are returned are static in memory and won't be moved/deleted after returning from the function, or you have to pass a destination pointer into the function and instead copy the return string into the given memory, or you could just use C++ strings and return by value.

Pointers may not be too hard to understand, but they probably gained their reputation as being "difficult to master" because of the possible problems that can be caused if you're not careful with them.


Just as a general hint: forget books that tell you that you learn a massive language like java, C++, C# in X days if X is smaller than 49
You just won't, no mather what you do. You at best get a brief overview which in the end harms more than it helps.



Granted, you wont remember a whole lot of stuff from a book, but if 20% of it sinks in, thats still quite a bit learnt.

I keep books like that for the auld pap housing, when learning C++ myself, I always had a 'How to teach a ginger C++ in 24 hours', and even though I never had it by my side when at a PC, it still helped.

What I did have by my side was C++: A Complete Reference, by a bloke called Herbert Schildt, and used this, inconjunction with BlitzPlus, to write userlibs. Sure damn beat crappy little console apps! :D


Sad that there are no head first books for C, at least I don't think so. If they are, they are definitely the more or less best resource to learn it. (I've 3 of them and they are great and will teach it in a way that takes care you learned it without beeing dry and useless or usefull at best as a "check back compendium")



Herbert Schildt's C++ reference book comes in two sections, the first section is about C, and C only, the second section expands upon it by showing you the aspects that make the language C++. This was excellent in a sense that, yes, you learnt C, which is enough for anyone, but when you hit the OOP, you were instantly geared up for it. Which was nice! :D

I don't see the problem with learning C++ directly - you don't HAVE to use the OOP right away you know. For example, cin and cout (which are C++ only) are much easier to use than scanf (not even supported anymore) and printf. Also those handy // comments that let you comment an entire line, yep they won't work in C. (not pure C anyway) Also in pure C you have to declare all the variables you are going to use in a function, at the start of the function.

Here's a question:

What if I wanted to rewrite my particle system in C++? Obviously, I'd stay away from drawing routines in C++ (let bmax handle that) but would doing the math and stuff be quicker in C++? How hard would it be to do this?

Here's my particle system, anyone can use it, I don't care:


Private
Global ParticleList:TList = CreateList()


Rem
bbdoc: Particle object type
about: Handles particles
EndRem
Type TParticle
	Field x:Float,y:Float,a:Float = 1,r:Int
	Field ox:Int,oy:Int
	Field img:TImage
	Field dx:Float,dy:Float, da:Float
	Field maxdistance:Int
	Field speed:Float
	Field dir:Int
	Field fade:Int
	Field z:Int
	
	Method Create:TParticle(_x:Int, _y:Int, _img:TImage, _dir:Int = 0, _speed:Float = 0, frames:Int = 1, _fade:Int = False, _autorot:Int = False, _z:Int = 0)
		ListAddLast(ParticleList,Self)
		z = _z
		x = _x
		y = _y
		ox = _x
		oy = _y
		img = _img
		speed = _speed
		dir = _dir
		dx = Sin(dir) * speed
		dy = -Cos(dir) * speed
		da = 1.0 / frames
		maxdistance = frames
		If dir And _autorot
			r = -dir - 180
		End If

		If _fade
			fade = True
		End If
	End Method
	
	Method Update:TParticle()
		x:+dx
		y:+dy
		If fade a:-da
		SetRotation(r)
		SetAlpha(a)
		DrawImage img,x,y
		SetRotation(0)
		SetAlpha(1)
		
		maxdistance:- 1
		If Not maxdistance Then
			Destroy()
		End If
		
		If x > GraphicsWidth() Or x < 0 - ImageWidth(img) Or y > GraphicsHeight() Or y < 0 - ImageHeight(img)
			Destroy()
		End If
	End Method
	
	
	Method SetPAlpha(alpha:Float)
		a = alpha
	End Method
	
	Method SetPRotation(rot:Int)
		r = rot
	End Method
	
	Method Destroy()
		ParticleList.Remove(Self)
	End Method
	
	Method AddX(_x:Int)
		x:+ _x
	End Method
	
	Method AddY(_y:Int)
		y:+ _y
	End Method
	
	Method SetDirection(_dir:Int)
		dir = _dir
	End Method
	
	Method SetSpeed(_speed:Float)
		speed = _speed
	End Method
	
End Type


Public


Rem
bbdoc: ParticleExplosion creator
about: Creates a particle explosion at X and Y with Image with a certain N of particles, that lasts a certain amount of Frames and can have a SpeedMultiplyer, and a Z location(to specify where rendered)
returns: Nothing
EndRem
Function ParticleExplosion(_x:Float, _y:Float, image:TImage, n:Int, frames:Int, speed_multiplyer:Float = 0, ar:Int = False, _z:Int = 0)
	Local speed:Float
	
	For Local i:Int = 1 To n
		Local dir:Int = Rand(0, 359)
		
		If speed_multiplyer
			speed = Rnd(0.08*speed_multiplyer, 1.5*speed_multiplyer)
		Else
			speed = Rnd(0.08, 1.5)
		End If
		
		Local part:TParticle = New TParticle.Create(_x, _y, image, dir, speed, frames - 10 + Rand((frames*1.40)), True, ar, _z)
	Next
	
End Function

Rem
bbdoc: Particle creator
about: Creates a particle at said point with said attributes
returns: Nothing
EndRem
Function EmitParticle(_x:Float, _y:Float, image:TImage, frames:Int, fade:Int = True, dir:Int = 0, speed:Float = 0, ar:Int = False, _z:Int = 0)

	Local part:TParticle = New TParticle.Create(_x, _y, image, dir, speed, frames, fade, ar, _z)

End Function

Rem
bbdoc: Particle count function
about: Returns the particle count
returns: The particle count
End Rem
Function ParticleCount:Int()
	Return ParticleList.Count()
End Function

Rem
bbdoc: Clear particles function
about: Clears all particles
returns: Nothing
End Rem
Function ClearParticles()
	ParticleList.Clear()
End Function

Rem
bbdoc: Clear particlesZ function
about: Clears all particles on the given Z level.
returns: Nothing
End Rem
Function ClearParticlesZ(z:Int = 0)
	For Local delp:TParticle = EachIn ParticleList
		If delp.z = z
			ParticleList.Remove(delp)
		End If
	Next
End Function

Rem
bbdoc: Particle update routine
about: Updates particles at said Z level, you can add a optional force routine for things such as gravity.
returns: Nothing
EndRem
Function UpdateParticlesZ(z:Int = 0, forcex:Float = 0, forcey:Float = 0)	
	For Local UpdateP:TParticle = EachIn ParticleList
		If UpdateP.z = z
			UpdateP.Update()
			If forcex UpdateP.x:+forcex
			If forcey UpdateP.y:+forcey
		End If
	Next
End Function


Also in pure C you have to declare all the variables you are going to use in a function, at the start of the function.

True, that's one good reason to start with C++ (in addition to the handy // comments, etc.) - C's requirement that all variables be declared at the start of the function is not only tedious but usually results in far messier code than what C++ allows, so I guess it's best to start with C++ and learn good habits from the beginning. Like you say, there's no need to learn the OOP features until you're ready, because unlike Java/C#, C++ does not force you to use OOP everywhere.

Nor does C++ force you to first think and then code the next trashy hacky instable code ...

Constraints normally help to get a given structure, not to prevent you from beeing creative.
C++ so far to me mainly has shown creativity in how you are not meant to program modern OO applications, but only rarely the opposite at least when it comes to game technology.

2 questions:

1. How do you 'wrap' C++ to blitzmax? It's easy with simple functions returning strings or ints or simple data types... but what about classes/objects? how do you do this?

2. How do you get C++ classes and stuff working? and is there such thing as lists in C++?

Here's what i'm trying to do:

C++
#include <string>

using namespace std;

extern "C" {
    class cParticle {
    public:
          float x;
          float y;
          
          void Update(void) {
               x++;
               y++;
          }     
    };
    
    
    cParticle cCreateParticle(void) {
         return new cParticle; // is this right?
    }
    
    void cDeleteParticle(cParticle p) {
         delete p; // is this right?
    }
    
    void cUpdateParticle(cParticle p){
         p.Update(); // what about this one?
    }
    float ParticleX(cParticle p) {
          return p.x;
    }
    float ParticleY(cParticle p) {
          return p.y;
    }
}


and in bmax:

Import "main.cpp"


Extern "C"
	Function cCreateParticle()'What do I return?
	Function cUpdateParticle('What goes in here?)
	Function cDeleteParticle('What goes in here?)
	Function ParticleX:Float('what goes in here?)
	Function ParticleY:Float('what goes in here?)
End Extern

'What data type? 
Local part = cCreateParticle()

Print ParticleX(part)+" , "+ParticleY(part)

cUpdateParticle(part)

Print ParticleX+" , "+ParticleY

cDeleteParticle(part)

Rem
this should print:
0 , 0
1 , 1
End Rem


End


Dunno if it helps, but may help you along with lists, which i have recently learned how to use.

But here is some C++ code i wrote using lists etc. Dont take it as gospel though ive no idea if this 'leaks' (still learning that bit :) but it seems stable enough on linux XP and vista so im guessing it works ok :P

Its a bullet manager for a simple shooter im writing to to learn C++ better.

I am using my own typedefs (ie D_LIST is actually std::list) I do this because im not sure which types/classes i want to use yet. (and its easier than changing loads of assignments)

eg.
typedef std::string   D_STRING;
typedef irr::c8          D_CHAR;
typedef irr::s32        D_INT;
typedef std::list       D_LIST;
etc...

Here is the bullet class.
//----------------------------------------------------------------------------
//--------------------------Bullet class & managers---------------------------
//----------------------------------------------------------------------------
const D_INTu   BULLET=1;
const D_INTu   LASER=2;

class Cbullet
{
public:
    D_FLOAT x,y,lasertimer;
    D_NODE * h;
    D_BOOL rem;
    D_INTu style;
    D_INTu power;

    Cbullet(D_FLOAT,D_FLOAT,D_INTu,D_INT,D_INTu);
    ~Cbullet();

    void updatebullet();

};

//Bullet Constructor - What automatically hapens when bullet is created ( =new Cbullet )
Cbullet::Cbullet(D_FLOAT sx,D_FLOAT sy,D_INTu sty,D_INT bulletangle,D_INTu powerlevel)
{
    rem=false;
    style=sty;
    power=powerlevel;
    x=sx;
    y=sy;
    power=powerlevel;
    switch (sty)
    {
        case BULLET:
            h=CreateINodeFromIMesh(medialib.quad);
            NodeTexture(h,medialib.bullet);
            h->setMaterialType(irr::video::EMT_TRANSPARENT_ALPHA_CHANNEL);
            ScaleNode(h,1,.5*powerlevel,1);
            NodeFX(h,1);
            PositionNode(h,sx,sy,0);
            RotateNode(h,0,0,bulletangle);
            break;
        case LASER:
            lasertimer=1.0f;
            break;
    }
}

//Bullet Destructor - What automatically happens when bullet is "delete"-ed.
Cbullet::~Cbullet()
{
    h->remove();
}

//Updater
void Cbullet::updatebullet()
{
    rem=false;

    switch (style)
    {
        case BULLET:
            MoveNode(h, 5.0f,0,0);
            x=NodeX(h);
            y=NodeY(h,true);
            if (x<0 || x>640 || y<0 || y>480) rem=true;
            break;

        case LASER:
            //laser code here
        break;
    }
}

//end of bullet class---------------------------------------------------------
Make a list to store many bullets
//declare a std::list
D_LIST <Cbullet*> bulletlist;
A mainloop-called function to manage the bullets' list
//Update all bullets currently active in list (called in main loop)
void updateWeapons()
{
   int bulletcount = 0;
   D_LIST <Cbullet*>::iterator i;
   for (i = bulletlist.begin(); i != bulletlist.end(); ++i)
   if (!bulletlist.empty())
   {
        (*i)->updatebullet();
        if((*i)->rem)
        {
            delete (*i);
            i=bulletlist.erase(i);
        }
  }
}

Function that is called when fire is pressed.
//Function to fire off a volley of bullets depending on type, powerlevel and direction
void fireWeapons(D_FLOAT sx,D_FLOAT sy,D_INTu directional,D_INTu powerlevel)
{
    Cbullet *b;
    b=new Cbullet(sx+10,sy,BULLET,0,powerlevel);  bulletlist.push_back(b);
    if (directional>1)
    {
        b=new Cbullet(sx-10,sy,BULLET,180,powerlevel);  bulletlist.push_back(b);
    }
    if (directional>2)
    {
        b=new Cbullet(sx+10,sy-5,BULLET,345,powerlevel); bulletlist.push_back(b);
        b=new Cbullet(sx+10,sy+5,BULLET,15,powerlevel); bulletlist.push_back(b);
    }
    if (directional>3)
    {
        b=new Cbullet(sx,sy,BULLET,270,powerlevel); bulletlist.push_back(b);
        b=new Cbullet(sx,sy,BULLET,90,powerlevel); bulletlist.push_back(b);
    }
}


No idea how to access this in bmax though.

I'm not sure about wrapping to BlitzMax, but the C++ code has some problems:
    cParticle cCreateParticle(void) {
         return new cParticle; // is this right?
    }
    
    void cDeleteParticle(cParticle p) {
         delete p; // is this right?
    }


In C++ you can pass by value (which copies the object), or by reference or pointer. Here you're passing and returning a copy of the object, which is not right. cDeleteParticle() is going to copy the object, then delete it, which actually does nothing to the original object (in fact it may even crash because you can't delete an object that you didn't create with "new").

Here's how it should be:
    cParticle *cCreateParticle(void) {
         return new cParticle;
    }
    
    void cDeleteParticle(cParticle *p) {
         delete p;
    }


BlitzMax uses a garbage collection system, so everything is basically a pointer, but in C++ you need to make the distinction between passing pointers or passing a copy of the whole object.

Here's some extract from a game I made (using Strict):
Extern
	Type gametype
		Method restart(x, y, mines)
		Method getsquare(x, y, showall)
		Method makemove(x, y)
		Method getmineshit()
		Method getmoves()
		Method gameover()
		Method getremaining()
		Method getmines()
		Method toggleflag(x, y)
		Method getflag(x, y)
		Method getflagnum()
		Method hitmine(x, y)
	End Type
	Function newgame:gametype(x, y, mines)
	Function endgame(game:gametype)
End Extern;


C++ :
class gametype
{
	Private stuff
	...
Public:
	gametype(int x, int y, int mines)
    {
	  startnewgame(x, y, mines);
    }
    virtual void restart(int x, int y, int mines)
    {
	  board.clearboard();
	  startnewgame(x, y, mines);
    }
    virtual int getsquare(int x, int y, bool showall)
    {}
     ETC
}

extern "C"
{
    gametype* newgame(int x, int y, int mines)
    {
	  return new gametype(x, y, mines);
    }
    void endgame(gametype* game)
    {
	  delete game;
    }
}


Forgive the messed up formatting.

Back in BMX
Local game:gametype = newgame(xsize, ysize, mines)
game.makemove(mouseonx, mouseony)
ETC


Note: each method you want to be able to use in Blitzmax, must be defiend in BMX extern in ORDER they appear in C++ with parameters, and in C++ must be listed as virtual and public. Look at the end of C++ file, you'll need a create and delete function that makes and returns your class, and frees your class. Remember no garbage collector! Call delete function in BMX when done!

Sorry I don't have time for more detail but hopefully you can get some ideas from this.

I've gotten it to work, thanks guys, the main thing that helped me is that blitzmax uses pointers only. anyways here's the updated code(I also didnt define update):

C++
#include <string>

using namespace std;

extern "C" {
    class cParticle {
    public:
          float x;
          float y;
          
          void Update(void); 
    };
    
    void cParticle::Update() {
         x++;
         y++;
    }
    
    cParticle *cCreateParticle(void) {
         return new cParticle; // is this right?
    }
    
    void cDeleteParticle(cParticle *p) {
         delete p; // is this right?
    }
    
    void cUpdateParticle(cParticle *p){
         p->Update(); // what about this one?
    }
    float ParticleX(cParticle *p) {
          return p->x;
    }
    float ParticleY(cParticle *p) {
          return p->y;
    }
}


bmax:
SuperStrict

Import "main.cpp"


Extern "C"
	Function cCreateParticle:Byte Ptr()
	Function cUpdateParticle(p:Byte Ptr)
	Function cDeleteParticle(p:Byte Ptr)
	Function ParticleX:Float(p:Byte Ptr)
	Function ParticleY:Float(p:Byte Ptr)
End Extern

'What data type? 
Local part:Byte Ptr = cCreateParticle()

Print ParticleX(part)+" , "+ParticleY(part)

cUpdateParticle(part)

Print ParticleX(part)+" , "+ParticleY(part)

cDeleteParticle(part)


End


alright, new problem.

I've been sitting here trying to get this to work for hours, maybe one of you guys knows what i'm doing wrong:

Problem: It's not drawing anything, what??

c++
#include <math.h>
#define DEG_TO_RAD 0.0174532925199432957692369076848861

//Functions to grab a Radian sin/cos not in degrees.
double Sin2( double ang ){
	return sin( ang*DEG_TO_RAD );
}
double Cos2( double ang ){
	return cos( ang*DEG_TO_RAD );
}

// All the stuff that can be accessed in bmax
extern "C" {

    // our particle class
    class cParticle {
    public:
          // all the variables associated with a particle
          float x;
          float y;
          float a;
          int r;
          float dx;
          float dy;
          float da;
          int maxdistance;
          float speed;
          int dir;
          int fade;
          int z;
          
          // constructor (AKA Create())
          cParticle(float, float, int, float, int, bool, bool, int);
          // destructor have not found a use yet
          ~cParticle();
          
          //Update particle
          void Update(void); 
    };
    
    // Our class functions redefined:
           
    // constuctor
    cParticle::cParticle(float _x, float _y, int _dir = 0, 
                               float _speed = 0, 
                          int frames = 1, bool _fade = false, 
                          bool _autorot = false, int _z = 0) {
                
  		z = _z;
		x = _x;
		y = _y;
		speed = _speed;
		dir = _dir;
		dx = (Sin2(dir) * speed); 
		dy = (-Cos2(dir) * speed);
		da = 1.0 / frames;
		maxdistance = frames;
		if(dir > 0&&_autorot > 0){
			r = -dir - 180;
		}

		if(_fade > 0) {
			fade = true;
        }
                               
    
    }
    //destructor
    cParticle::~cParticle() {
        
        // code for destructor
    }      
    
             
    void cParticle::Update() {
		x=x+dx;
		y=y+dy;
    }
    
    
    // mainsteam functions:
                 
    // Wrap function to create a particle
    cParticle *cCreateParticle(float _x, float _y, int _dir = 0, 
                               float _speed = 0, 
                          int frames = 1, bool _fade = false, 
                          bool _autorot = false, int _z = 0) {
         cParticle *p; // particle that we will return
         p = new cParticle(_x, _y, _dir, 
                           _speed, frames, 
                           _fade, 
                           _autorot, _z); // basicly shove the arguments of this function into a constructor
         return p;
    }
    
    //Wrap function to delete a particle
    void cDeleteParticle(cParticle *p) {
         delete p;
    }
    
    //Wrap function to update a particle
    void cUpdateParticle(cParticle *p){
         p->Update();
    }
    
    //functions to get various states of a particle
    float cPX(cParticle *p) {
          return p->x;
    }
    float cPY(cParticle *p) {
          return p->y;
    }
    float cPA(cParticle *p) {
          return p->a;
    }
}


bmax
SuperStrict

Import "main.cpp"

'Wrap functions from the particle C++ code
Extern "C"
	Function cCreateParticle:Byte Ptr(_x:Int, _y:Int, _dir:Int = 0, _speed:Float = 0, frames:Int = 1, _fade:Int = False, _autorot:Int = False, _z:Int = 0)
	Function cUpdateParticle(p:Byte Ptr)
	Function cDeleteParticle(p:Byte Ptr)
	Function cPX(p:Byte Ptr)
	Function cPY(p:Byte Ptr)
	Function cPA(p:Byte Ptr)
End Extern

'TParticle type, basicly a wrapper w/ drawing functions for the class counterpart.
Global ParticleList:TList = CreateList()
Type TParticle
	Field img:TImage
	Field cBuddy:Byte Ptr
	
	
	Method Create:TParticle(_x:Int, _y:Int, _img:TImage, _dir:Int = 0, _speed:Float = 0, frames:Int = 1, _fade:Int = False, _autorot:Int = False, _z:Int = 0)
		'create a "c" particle and give it's handle to the cbuddy variable
		cBuddy = cCreateParticle(_x, _y, _dir, _speed, frames, _fade, _autorot, _z)
		'Add this object to the particle list
		ListAddLast(ParticleList,Self)
		'Add given image to the object
		img = _img
	End Method
	
	Method Update()
		'Update the "c" particle
		cUpdateParticle(cBuddy)
		'Grab the new x/y positions of the "c" particle(so we only have to use this function once per loop)
		Local x:Float = cPX(cBuddy)
		Local y:Float = cPY(cBuddy)
		'Draw the given img at the "c" Particle's locations 
		DrawImage img,x,y
	End Method
	
End Type


'init graphics
AppTitle = "C++ Particle Test"
Graphics 800,600


'Create Dot image
Local dot:Timage = CreateImage(10,10)
DrawOval 0,0,10,10
GrabImage dot,0,0

'main loop
While Not KeyHit(KEY_ESCAPE)
Cls

	'create a particle at the mouse's location, then update all particles
	Local part:TParticle = New TParticle.Create(MouseX(),MouseY(),dot)
	For Local i:TParticle = EachIn ParticleList
		i.Update()
	Next

Flip 1
Wend

End


Now I think this is on the blitzmax side, because even if the C++ side was screwed, it would still return '0' on the position code, thus it would at least draw a circle at 0,0 right? well, its not, and I cant figure out why, because the List/Bmax TParticle looks correct.

In your bmx cCreateParticle code you have x/y as ints, but on the c++ side you're using floats ;)

Its also missing the return type for cPX ect in you're bmx extern block, so it should be...
Extern "C"
	Function cCreateParticle:Byte Ptr(_x:Float, _y:Float, _dir:Int = 0, _speed:Float = 0, frames:Int = 1, _fade:Int = False, _autorot:Int = False, _z:Int = 0)
	Function cUpdateParticle(p:Byte Ptr)
	Function cDeleteParticle(p:Byte Ptr)
	Function cPX:Float(p:Byte Ptr)
	Function cPY:Float(p:Byte Ptr)
	Function cPA:Float(p:Byte Ptr)
End Extern


Just caught that. Now it shows on the screen, but only in the upper right cornor, it should create a particle every loop on the mouse's coords.


here's the updated code:

C++
#include <math.h>
#define DEG_TO_RAD 0.0174532925199432957692369076848861

//Functions to grab a Radian sin/cos not in degrees.
double Sin2( double ang ){
	return sin( ang*DEG_TO_RAD );
}
double Cos2( double ang ){
	return cos( ang*DEG_TO_RAD );
}

// All the stuff that can be accessed in bmax
extern "C" {

    // our particle class
    class cParticle {
    public:
          // all the variables associated with a particle
          float x;
          float y;
          float a;
          int r;
          float dx;
          float dy;
          float da;
          int maxdistance;
          float speed;
          int dir;
          int fade;
          int z;
          
          // constructor (AKA Create())
          cParticle(float, float, int, float, int, bool, bool, int);
          // destructor have not found a use yet
          ~cParticle();
          
          //Update particle
          void Update(void); 
    };
    
    // Our class functions redefined:
           
    // constuctor
    cParticle::cParticle(float _x, float _y, int _dir = 0, 
                               float _speed = 0, 
                          int frames = 1, bool _fade = false, 
                          bool _autorot = false, int _z = 0) {
                
  		z = _z;
		x = _x;
		y = _y;
		speed = _speed;
		dir = _dir;
		dx = (Sin2(dir) * speed); 
		dy = (-Cos2(dir) * speed);
		da = 1.0 / frames;
		a = 1.0;
		maxdistance = frames;
		if(dir > 0&&_autorot > 0){
			r = -dir - 180;
		}

		if(_fade > 0) {
			fade = true;
        }
                               
    
    }
    //destructor
    cParticle::~cParticle() {
        
        // code for destructor
    }      
    
             
    void cParticle::Update() {
		x=x+dx;
		y=y+dy;
		if( fade == true ) { a=a-da; }
		maxdistance--;
    }
    
    
    // mainsteam functions:
                 
    // Wrap function to create a particle
    cParticle *cCreateParticle(float _x, float _y, int _dir = 0, 
                               float _speed = 0, 
                          int frames = 1, bool _fade = false, 
                          bool _autorot = false, int _z = 0) {
         cParticle *p; // particle that we will return
         p = new cParticle(_x, _y, _dir, 
                           _speed, frames, 
                           _fade, 
                           _autorot, _z); // basicly shove the arguments of this function into a constructor
         return p;
    }
    
    //Wrap function to delete a particle
    void cDeleteParticle(cParticle *p) {
         delete p;
    }
    
    //Wrap function to update a particle
    void cUpdateParticle(cParticle *p){
         p->Update();
    }
    
    //functions to get various states of a particle
    float cPX(cParticle *p) {
          return p->x;
    }
    float cPY(cParticle *p) {
          return p->y;
    }
    float cPA(cParticle *p) {
          return p->a;
    }
    int cPR(cParticle *p) {
        return p->r;
    }
    int cPLife(cParticle *p) {
        return p->maxdistance;
    }
}


bmx
SuperStrict

Import "main.cpp"

'Wrap functions from the particle C++ code
Extern "C"
	Function cCreateParticle:Byte Ptr(_x:Int, _y:Int, _dir:Int = 0, _speed:Float = 0, frames:Int = 1, _fade:Int = False, _autorot:Int = False, _z:Int = 0)
	Function cUpdateParticle(p:Byte Ptr)
	Function cDeleteParticle(p:Byte Ptr)
	Function cPX:Float(p:Byte Ptr)
	Function cPY:Float(p:Byte Ptr)
	Function cPA:Float(p:Byte Ptr)
	Function cPR:Int(p:Byte Ptr)
	Function cPLife:Int(p:Byte Ptr)
End Extern

'TParticle type, basicly a wrapper w/ drawing functions for the class counterpart.
Global ParticleList:TList = CreateList()
Type TParticle
	Field img:TImage
	Field cBuddy:Byte Ptr
	
	Method Create:TParticle(_x:Float, _y:Float, _img:TImage, _dir:Int = 0, _speed:Float = 0, frames:Int = 1, _fade:Int = False, _autorot:Int = False, _z:Int = 0)
		'create a "c" particle and give it's handle to the cbuddy variable
		cBuddy = cCreateParticle(_x, _y, _dir, _speed, frames, _fade, _autorot, _z)
		'Add this object to the particle list
		ListAddLast(ParticleList,Self)
		'Add given image to the object
		img = _img
	End Method
	
	Method Update()
		'Update the "c" particle
		cUpdateParticle(cBuddy)
		'Grab the new x/y positions of the "c" particle(so we only have to use this function once per loop)
		Local x:Float = cPX(cBuddy)
		Local y:Float = cPY(cBuddy)
		
		If cPLife(cBuddy) = 0 Or x > GraphicsWidth()+ImageWidth(img) Or x < 0-ImageWidth(img) Or y > GraphicsHeight()+ImageHeight(img) Or y < 0-ImageHeight(img)
			Destroy()
			Return
		End If
		
		'Draw the given img at the "c" Particle's locations 
		SetAlpha cPA(cBuddy)
		SetRotation cPR(cBuddy)
		DrawImage img,x,y
		SetAlpha 1
		SetRotation 0
	End Method
	
	Method Destroy()
		ParticleList.Remove(Self)
		cDeleteParticle(cBuddy)
	End Method
	
End Type


'init graphics
AppTitle = "C++ Particle Test"
Graphics 800,600


'Create Dot image
Local dot:Timage = CreateImage(10,10)
DrawOval 0,0,10,10
GrabImage dot,0,0

'main loop
While Not KeyHit(KEY_ESCAPE)
Cls

	'create a particle at the mouse's location, then update all particles
	Local part:TParticle = New TParticle.Create(MouseX(),MouseY(),dot,,,40)
	For Local i:TParticle = EachIn ParticleList
		i.Update()
	Next

Flip 1
Wend

End



In your bmx cCreateParticle code you have x/y as ints, but on the c++ side you're using floats ;)



Extern "C"
	Function cCreateParticle:Byte Ptr(_x:Float, _y:Float, _dir:Int = 0, _speed:Float = 0, frames:Int = 1, _fade:Int = False, _autorot:Int = False, _z:Int = 0)
...

:P

I just thought I'd mention, if you're trying to move your particle system to C++ while still keeping your other code in BlitzMax, I doubt you'll get much of a performance boost. Remember that simply calling a DLL function has a slight overhead, so it's not helpful unless the calculations are really intense. Not to mention that what you're doing looks really tedious.

BTW, C++ isn't as "easy" as BlitzMax in several ways. One of them you might not know about is that std::list isn't the fastest way to store a list of objects - there are other methods. I think I've noticed that adding and removing thousands of objects per second to BlitzMax's lists are actually slightly faster than doing so with std::list (due to one of the advantages of garbage collection). So if you want really fast allocation / deallocation of particles, try looking into other storage methods like std::vector or std::queue. Or if you want maximum speed, you could use a straight array of cParticle objects and manage them manually.

Not to mention that what you're doing looks really tedious

Its still a good way for you to get to grips with c++, so keep at it mate ;)

cool.

Here's my thoughts on C++ after screwing with it for two days:

-Its a powerful language
-Its decent once you get used to it
-I absolutely hate the semi colon at the end of each line
-Much faster than native bmax, and can be successfuly interfaced with bmax
-More flexibility at the cost of more complexity... can be good or bad depending on your prespective.


Overall, I like it, and I'm learning more and more each hour of messing with it.

Side effects:

Mostly typing data types infront of variables in blitzmax, that and putting semicolons all over the place in blitzmax


The particle system:

Is mostly ported. What I did was:

-Move all calculations/updating to C++
-Leave drawing and keeping track of them in bmax

I'm going to try to convert the blitzmax side of things to arrays, for extra speed, so far so good...

Speaking of arrays, don't they have special methods? like append ect? where is a list of these?

Question:

When converting to an array, I have an error with deleting the particle... does anyone know why?

'TParticle type, basicly a wrapper w/ drawing functions for the class counterpart.
Const MAX_PARTICLES:Int = 10000
Global ParticleList:TParticle[MAX_PARTICLES]
Global pCount:Int = 0


Type TParticle
	Field img:TImage
	Field cBuddy:Byte Ptr
	
	Method Create:TParticle(_x:Float, _y:Float, _img:TImage, _dir:Int = 0, _speed:Float = 0, frames:Int = 1, _fade:Int = False, _autorot:Int = False, _z:Int = 0)
		'create a "c" particle and give it's handle to the cbuddy variable
		cBuddy = cCreateParticle(_x, _y, _dir, _speed, frames, _fade, _autorot, _z)
		'Add given image to the object
		img = _img
		'Add this object to the particle list
		ParticleList[pCount] = Self
		pCount:+1
	End Method
	
	Method Update()
		'Update the "c" particle
		cUpdateParticle(cBuddy)
		'Grab the new x/y positions of the "c" particle(so we only have to use this function once per loop)
		Local x:Float = cPX(cBuddy)
		Local y:Float = cPY(cBuddy)
		
		If cPLife(cBuddy) = 0 Or x > GraphicsWidth()+ImageWidth(img) Or x < 0-ImageWidth(img) Or y > GraphicsHeight()+ImageHeight(img) Or y < 0-ImageHeight(img)
			Destroy()
			Return
		End If
		
		'Draw the given img at the "c" Particle's locations 
		SetAlpha cPA(cBuddy)
		SetRotation cPR(cBuddy)
		DrawImage img,x,y
		SetAlpha 1
		SetRotation 0
	End Method
	
	Method Destroy()
		cDeleteParticle(cBuddy)
		ParticleList[pCount-1] = Self
		pCount:-1
	End Method
	
End Type


It's giving me a memory error on the cDeleteParticle command, probably because the copied particle's cBuddy pointer is already deleted...

How do I check if the pointer is deleted or not? I tried creating a "dead" field and just turning it true once the deletion process was done, then just check that, and if it's not dead then delete the cBuddy pointer. But now it just crashes without an error when a particle is destroyed.

here's that code:
'TParticle type, basicly a wrapper w/ drawing functions for the class counterpart.
Const MAX_PARTICLES:Int = 10000
Global ParticleList:TParticle[MAX_PARTICLES]
Global pCount:Int = 0


Type TParticle
	Field img:TImage
	Field cBuddy:Byte Ptr
	Field dead:Int
	
	Method Create:TParticle(_x:Float, _y:Float, _img:TImage, _dir:Int = 0, _speed:Float = 0, frames:Int = 1, _fade:Int = False, _autorot:Int = False, _z:Int = 0)
		'create a "c" particle and give it's handle to the cbuddy variable
		cBuddy = cCreateParticle(_x, _y, _dir, _speed, frames, _fade, _autorot, _z)
		'Add given image to the object
		img = _img
		'Add this object to the particle list
		ParticleList[pCount] = Self
		pCount:+1
	End Method
	
	Method Update()
		'Update the "c" particle
		cUpdateParticle(cBuddy)
		'Grab the new x/y positions of the "c" particle(so we only have to use this function once per loop)
		Local x:Float = cPX(cBuddy)
		Local y:Float = cPY(cBuddy)
		
		If cPLife(cBuddy) = 0 Or x > GraphicsWidth()+ImageWidth(img) Or x < 0-ImageWidth(img) Or y > GraphicsHeight()+ImageHeight(img) Or y < 0-ImageHeight(img)
			Destroy()
			Return
		End If
		
		'Draw the given img at the "c" Particle's locations 
		SetAlpha cPA(cBuddy)
		SetRotation cPR(cBuddy)
		DrawImage img,x,y
		SetAlpha 1
		SetRotation 0
	End Method
	
	Method Destroy()
		If Not dead cDeleteParticle(cBuddy)
		ParticleList[pCount-1] = Self
		pCount:-1
		dead = True
	End Method
	
End Type


the C++ code is the same

-I absolutely hate the semi colon at the end of each line

It's pretty easy to get used to over time, fortunately.

Speaking of arrays, don't they have special methods? like append ect? where is a list of these?

I'm not sure of all the array classes, but one is std::vector, which is dynamically resized as you add new values, in an efficient way. The fastest possible arrays in C++ are native arrays:

float myArray[100];  //static array

Or:
float *myArray; //or "float myArray[];"
myArray = new float[100];
delete[] myArray;


This type of array is the fastest, but the most simple and most unprotected way to use arrays. There's no bounds checking, so if you write to element #129 in a 100 size array, there will be no error (just unknown behavior). But because it doesn't have to check the bounds, etc., etc., it's very fast. Basically it's direct memory access.

Cool, but i'm doing the array stuff on the bmax side of things, to avoid having to do a loop for updating and a loop for drawing..

What about my question above your post, i'm still stumped, why is it crashing?

Hint: if you want to learn C++, use C++ only. Blitzmax adds another source of error, and there are enough of those around already. :)

Interesing post...it should be 'sticky' or put in the tutorial.