PDA

View Full Version : Beginner's Programming Questions


jester
July 5th, 2004, 06:40 AM
Hey,

I recently started programming C++ - like, 2 weeks ago, and it's pretty interesting. I'm just getting functions, do, whiles, if, elses etc to work at the moment, but I'm understanding it pretty well, it's cool.

So the question I'm asking is... how long would it take before I would be good enough to program some features into Legacy? How long have you guys been programming?

BTW it rocks you guys are making a C++ version, it makes it easier for new programmers like me to do some Legacy editting later!

Exl
July 5th, 2004, 06:46 AM
After the things you mentioned up there there's still classes, general game mechanics, finite state machines, structures, typedefs, casting, binary operators, polymorphism, inheritance and plenty of other stuff. You'll be busy for the next couple of years mastering those.

Hurdler
July 5th, 2004, 09:28 AM
In fact, once you've learned a language, you have to learn algorithmic and the libraries we use.

But don't be afraid, even if it can take years, you can already do some simple things. For instance, writing a new FS function can be quite easy.

Aliotroph?
July 5th, 2004, 10:24 PM
All hail typedefs and structs: pure genious! :D

As for classes and polymorphism, I never liked them in C++. Come to think of it, I still don't like polymorphism in Java. I guess my thinking is just too low level.

smite-meister
July 6th, 2004, 08:41 AM
It's possible to learn the language in a month or so, but it takes much longer to intuitively understand how things work and how they are supposed to work.

But don't let this depress you. As Hurdler said, although you can't necessarily write a new renderer after a few weeks of learning, you CAN write some smaller-scale stuff which can still be very useful to us.

jester
July 9th, 2004, 09:58 AM
So how long do you think it'd be before I could help you guys? I'm still learning away, even if some of it is pretty boring so far.

Like, what topics do you think I need to learn before I'm any use to you guys? I just have this big programming book I'm going through at the moment..

I mean, you said that I could write some smaller stuff after a few weeks... don't I need to understand most of Legacy to write stuff for it?

Hurdler
July 9th, 2004, 10:51 AM
If you know enough stuff about doom at the editing level and you become comfortable with C/C++, it won't be too much difficult to understand some part of the source code.

You don't need to understand all the source code. In fact, I don't know all the Legacy source code myself. There are lots of parts I have never touched. When I started coding the OpenGL renderer, I didn't touch anything else than the "hardware" directory, and even that one I haven't touch a lot. That's only when I started doing debug stuff or adding new features I really looked at other parts of the source code.

Pate
July 16th, 2004, 02:46 AM
A good way to get started is to add compilation options -Wall and -pedantic, and start cleaning up the warnings that pop up. Might be a bit tedious, though.

jester
July 23rd, 2004, 09:34 AM
Awesome.

Well, I'm still programming, so I guess I'll download the source code when I get my internet connection sorted out... I'm just using the library computers at the moment (can't really afford a home internet connection at the mo, bit broke, not worth it for the time I spend online etc.), and you can't do downloads on them.

But yeah, I'm still learning C++ so I should be able to be of some use hopefully, someday! I'll probably get the source in a coupla weeks of a friend's computer anyway...

Just a question. Do you need any kind of special compiler to compile it or will Quincy's or the one that comes with Microsoft Visual C++ do the trick?

Cheers!

Pate
July 23rd, 2004, 01:36 PM
Check out compiling.html in the docs directory. It has the info you need.

Currently you can't compile C++ Legacy with MSVC, and creating the workspace files etc might be a chore. But a nice beginner's job (which would yield tangible results very fast) would be fixing the Legacy Launcher. There are lots of annoying small bugs in it, which would require fixing. Unfortunately most of the Legacy dev team is on Linux / MacOSX, so the Windows launcher is given very little attention. The launcher has developer studio workspace files and stuff, so you would get started quite easily.

Aliotroph?
July 23rd, 2004, 01:40 PM
Hehehe, I was tempted to have a go at fixing that launcher at one point. I'm just too lazy to install Visual Studio. I have the .NET version so I'm not sure if I'd have to modify the code. I'd rather not end up with a launcher wanting the .NET framework.

Pate
July 23rd, 2004, 01:47 PM
You can't end up with a .NET version of the launcher without a total rewrite. The only languages supporting .NET are (IIRC) C# and Visual Basic#, while the launcher is written in C++.

Aliotroph?
July 23rd, 2004, 02:16 PM
That puts me at ease. It wouldn't have surprised me though if MS redesigned their C++ compiler so it happily compiled things so they need the .NET stuff. They like to hijack languages. I noticed VB projects requiring .NET stuff when they didn't use any of it. I wrote a Minesweeper clone in VB and it wouldn't run on my friend's PC until he ran Windows Update. I was shocked.

Hurdler
July 23rd, 2004, 02:38 PM
Visual Studio .NET has a C++ compiler, it's not an issue (the .NET in the name is plain stupid since you don't need to use the .NET framework). I've never tried it, but I suppose it should load VC6 projects without any problem and compile them without too much problem.

Aliotroph?
July 24th, 2004, 11:06 AM
I should hope so. Not that I have a right to complain. I got my copy of Visual Studio 2002 for free at an M$ seminar.

jester
August 4th, 2004, 07:00 AM
BTW guys, any chance I could ask you a few questions about programming C++? It sure can be confusing sometimes.

smite-meister
August 4th, 2004, 10:57 AM
Shoot away :)

jester
August 9th, 2004, 07:03 AM
OK, basically, the first thing is that I'm trying to do this if statement, based on the user inputting either 1, 2, or 3 into an integer variable. So at the moment it looks something like this...

if (x = 1 | x = 2 | x =3)
{ blah blah do whatever }

but when I try this, it gives me an error when I compile. Basically it's a menu thing. I want it to tell the user to try again if they don't type in 1 2 or 3 for the input when they're asked.

Cheers.

Pate
August 9th, 2004, 07:32 AM
This is vary basic operator stuff that is covered in any entry-level C++ book. (You do have one, don't you? If not, visit a library or something, it'll save you tons of lost hair.)

Aliotroph?
August 9th, 2004, 09:11 PM
Ah, you mean:
if (x==1 || x==2 || x==3) { [code in here] }

You definitely need to grab a good book or a good tutorial from the web. :)

DaniJ
August 11th, 2004, 04:23 AM
A really good place to start is cplusplus.com (http://www.cplusplus.com/).

They have an online tutorial that is very good, it covers everything related to how you form the syntax, structs, pointers etc. However it lacks a bit on the why and the reasons for doing things one way instead of another. Though the latter generally comes from experience.

jester
August 25th, 2004, 06:56 AM
Guys, thanks for your advice, but I kinda messed up on my original question.

Basically, I had the code right for the bit that decides whether or not x is 1, 2 or 3. Now, here's the thing. I'm trying to make it so that a user can imput a number, and then that number can be used to get some information from a position in an array (position 1, 2 or 3!).

Which works fine. The only problem is, if a user inputs a character other than a number, my program screws up! Even if I tell the program that, if int x does not turn out to be 1, 2, or 3, that the program should convert x back to zero, the program still screws up, and starts printing crap all over the screen. It still compiles fine, mind.

I don't know if this will make sense to you guys, or even if it makes sense at all, but oh well. Any help would be appreciated. Maybe I'll post the program, if that would help. It's not very long.

CHEERS.

Aliotroph?
August 25th, 2004, 09:18 AM
Got the code for that? Different ways of grabbing input have different behaviours.

Ebola
August 25th, 2004, 01:01 PM
looks a whole lot like FS: :p


I went a Turbo Pascal class once. But I dunno I guess it wasn't for me. Atleast I passed. :)

Planky
August 25th, 2004, 02:43 PM
With Delphi (used to be pascal) there is a function called StrToIntDef which you could use to make sure the data entered was infact a valid integer:


if StrToIntDef(edit1.text, -1) = -1 then
showmessage('Invalid Integer')
else showmessage('Valid Integer');


I would imagine there is a C++ equivalent. Using something like that will only execute the code if the strtointdef condition is met, if not just have it pop up a message saying invalid or whatever

DaniJ
August 25th, 2004, 02:56 PM
It does sound like the problem is due to not qualifying the inputed value as an integer before you perform an opperation on it. As Aliotroph said it depends how your grabbing the input as to what it may be returning when you input a character. The best approach would be to check that the value IS an integer anyway just to be sure.

This might be useful: http://home.att.net/~jackklein/c/code/strtol.html

jester
August 27th, 2004, 06:48 AM
Okay, here's the full code for my program. It's not that long, so you should just be able to copy and paste it into your compiler, I think!BTW, the notes are there more for my benefit than anyone else's.. don't mean to be patronising!

Oh, and you'll probably recognise the names for the teams and the players- they're from Speedball 2, a classic game. I always wanted to be able to edit the teams in that. Although in the following program, you can only edit the team names so far.. I was trying to figure out how to sort out the integer inputting thing first.

Cheers!


#include <iostream>
#include <iomanip>

struct team // The structure declaration that declares the
{ // ingredients for each team structure.
int teamnum;
char teamname[20];
char ldef[20];
char goalie[20];
char rdef[20];
};

team teams[] = // An array of structures, containing all the data
{ // for all the teams.
{1,
"Brutal Deluxe",
"Colin",
"Barry",
"Gary" },

{2,
"Revolver",
"Matt",
"Boris",
"Graham" },

{3,
"Violent Desire",
"Steve",
"Chris",
"Jack" },

{-1,
"null",
"null",
"null",
"null" }
};

team* tp = teams; // A pointer to the array of structures
// that contains all the teams.

struct menu // Structure declaration for each option
{ // in a menu (options are structures containing
char option[30]; // a description of an option
void (*fnc)(); // and a pointer to a function.)
};

void viewbrut(); // All the different functions' prototypes.
void viewrevolver();
void viewteams();
void editteams();
void exitfunc();
void editplayers();
void editnames();
void editmain();

menu options[] = { // An initialisation of the options array
{ "Main menu.\n\nOptions:\n\n", 0}, // 0 and the structures in it.
{ "View teams\n", viewteams }, // 1
{ "Edit teams\n", editteams }, // 2
{ "Exit\n", exitfunc }, // 3
{ "Edit teams menu:\n\n", 0}, // 4
{ "Edit team names\n", editnames }, // 5
{ "Edit player names\n", editplayers }, // 6 These numbers are what
{ "Main menu\n", editmain } // 7 the user sees on screen.
}; // (minus the a integer)

// The following couple of lines relate to the choices integers, that
// is used to manouver around the menu structures, via pointers.

const int choices = sizeof options / sizeof (menu);

unsigned int choice = 0;
int a = 0; // Used by options array in main loop- tells it which is first
// option to be printed on screen
int y = 3; // and this tells it which is last.

int main()
{
while (choice != y) // y = exit number
{
if (choice > 0)
std::cout << std::endl << std::endl;
if (choice == 0)
{
std::cout << options[choice+a].option;
choice++;
}
for (choice; choice+a < y+1; choice++) // Print options on screen.
std::cout << choice << ": " << options[choice+a].option;
std::cout << std::endl;
choice = 0;
std::cin >> choice; // User inputs option number.
if (choice == 1 | choice == 2 | choice == 3) // Call the function.
{
std::cout << std::endl; // Keeps things clear & spaced out.
(*options[choice+a].fnc)();
}
else // if choice does not equal an option number
{
// The next line stops screw-ups when going back to start of
// while (choice != y) loop, otherwise might display
// option number -1 in the array etc
choice = 99;
std::cout << "Please choose again." << std::endl;
}
}
return 0;
}

void editteams()
{
a = 4;
y = 7;
choice = 0;
}
void editnames()
{
std::cout << "Team names editting options.\n\n"
<< "Input the number of the team name to edit:\n\n";
while (tp->teamnum != -1)
{
std::cout << tp->teamnum << ": " << tp->teamname;
if (tp->teamnum < 3)
std::cout << std::endl;
tp++;
}
std::cout << "\n4: Exit";
std::cout << "\n\n";
tp--; tp--; tp--;
std::cin >> tp->teamnum; // Find out how many times to increment
if (tp->teamnum > 0 && tp-> teamnum < 4)
{
tp = tp + tp->teamnum; tp--; // the tp pointer.

// char oldtn[20]; Could not get this to work for
// oldtn = tp->teamname; some reason.

std::cout << "\nType in the new name for " << tp->teamname << ": \n\n";
std::cin >> tp->teamname;
std::cout << "\nTeam renamed to: " <<
tp->teamname << ".\n\n ";
tp = tp - tp->teamnum; tp++;
}
tp->teamnum = 1;
choice = 0;
std::cout << std::endl;
}

void editplayers()
{
std::cout << "Player Editting Options.";
}

void editmain()
{
std::cout << "Exitting to main menu, I hope!\n\n";
choice = 0;
a = 0;
y = 3;
main();
}

void exitfunc()
{
std::cout << "Goodbye.\n";
}

void viewteams()
{
while (tp->teamnum != -1)
{
std::cout << tp->teamname << " Teamlist: \n"
<< "\nLdef: " << tp->ldef
<< "\nGoalie: " << tp->goalie
<< "\nRdef: " << tp->rdef;
if (tp->teamnum < 3)
std::cout << std::endl << std::endl;
tp++;
}
tp--; tp--; tp--;
choice = 0;
y = 3;
a = 0;
}

smite-meister
August 30th, 2004, 06:56 AM
A few points:
- Do not use 0 when you mean NULL. Usually it works, but it also makes it harder to understand your code
- Try to avoid global variables, or at least group them inside some global struct/class instance. For example tp should be made local in each function that uses it.
- Do not call main() inside your program, you'll eat up your stack. Just remove the call, you'll return to main() anyway when the function finishes.

Hurdler
August 30th, 2004, 07:14 AM
well, Bjarne Stroustrup, in his book, says to use 0 instead of NULL :p

Aliotroph?
August 30th, 2004, 01:13 PM
I had a good argument with a friend about using 0 this year. I used one to terminate a string and he got quite upset until I pointed out that the null character you use for that is ASCII 0 so it doesn't technically make a difference.

The use of the bitwise OR is interesting, but I don't think it makes a difference anyway in this case unless there's something I don't know about ==.

DaniJ
August 30th, 2004, 02:20 PM
Not wanting to hijack jester's thread but I've got a quick question I hoping one of you more experienced guys can help me with:

Is it possible to use a dynamically allocated array within a struct? Perhaps using typedef?

Hurdler
August 30th, 2004, 03:41 PM
what do you exactly mean by dynamically allocated array in a struct ?

if you mean something like (which is not correct C/C++)
struct MyStruct
{
int i;
int array[n];
int j;
};

main()
{
...
MyStruct a_struct;
...
}
with n the dynamic size of your array, the answer is no
but if you accept something like this:
struct MyStruct
{
int i;
int *array;
int j;
};

main()
{
...
MyStruct a_struct;
a_struct.array = new int[n];
...
}
then the answer is yes. But note that sizeof(a_struct) is "sizeof(int) + sizeof(int *) + sizeof(int)" and not "sizeof(int) + n * sizeof(int) + sizeof(int)"

DaniJ
August 31st, 2004, 04:39 PM
Jester - Can you edit your post and put your code into the <code> </code> tags. It's too hard to read atm.

Hurdler - Thanks a bunch! My codes now working flawlessly. *thumbs*

Hurdler
September 1st, 2004, 01:12 AM
great :) !

Pate
September 1st, 2004, 03:37 AM
Remember to delete the memory allocated to astruct.array when you are no longer using it. In this particular case you most likely want to replace the struct with a C++ class (making memory management easier) or use the vector class from Standard Template Library.

Here's a tutorial (http://cplus.about.com/library/weekly/aa050102a.htm) I found on using vectors & stuff.

jester
September 2nd, 2004, 06:05 AM
1. Smite Meister, about the call to main, basically I did that because if you look, the function that includes the call to main (editmain I think) will actually return to the middle of a loop otherwise.

I did have it with a goto statement or something, but main seemed to be more efficient in terms of the amount of code. Any ideas on how I should change it?

BTW thanks for the other points too. Very useful for learning, certainly a more interesting way to learn than just wading through page after page of my programming book.

2. And also... my original question really related to what happens when the user inputs something other than an integer in the menu choice selection screen. Try putting a letter in, and the program goes mental! At least it does with my compiler, Quincy 2002.

3. BTW Dani asked about putting my code in code and /code tags... I'm guessing a moderator or someone already did this? And this is why you can now scroll up and down it in it's own little window in the thread? If so, cheers!

Oh, and basically, cheers to anyone else who gave advice. Much appreciated!

Hurdler
September 2nd, 2004, 09:16 AM
1. Smite Meister, about the call to main, basically I did that because if you look, the function that includes the call to main (editmain I think) will actually return to the middle of a loop otherwise.

There is no good reason to do that. You should really avoid that since there is always a solution to such problem, and without any goto. It's just a matter of thinking how you could do that in another way. Believe me, if you don't do that, you'll regret it one day, when your program will become bigger or when you'll want to modify it.

DaniJ
September 3rd, 2004, 01:35 AM
I've got another quickie if anyone can help:

The bellow function works on everything but a string. When it prints the string it is showing as a symbol instead. Any ideas?

/EDIT: Heh, spoke too soon. I've fixed my problem.

smite-meister
September 3rd, 2004, 09:35 AM
about the call to main, basically I did that because if you look, the function that includes the call to main (editmain I think) will actually return to the middle of a loop otherwise.
Returning to the middle of the loop does no harm here, or does it?.

DaniJ
September 3rd, 2004, 09:54 AM
Is it possible to create pointer within structA, that points to the pointer to structB->member?
eg can I do this in a struct:

char *teset =*&(globals->confile);

Hurdler
September 3rd, 2004, 08:28 PM
yes sure. but you can't initialize the pointer in the struct itself, you must do that in the code, for instance:
struct structA
{
char *teset;
}
struct structB
{
char *confile;
}

int main()
{
structA a;
structB globals;
a.teset = globals.confile;
}

Don't know if that answer your question, or if you want to do something a bit different.

DaniJ
September 4th, 2004, 04:34 PM
Ahh. Thanks again Hurdler.

I took Alio's advice and have started converting my code to c++ classes but I've hit a problem and I can't seem to fix it. It's probably a really silly mistake but I can't see where I'm going wrong:

For some reason _printcomargs prints details of the last comarg, MAXNUMOFCOMARGS times instead of printing the details of every comarg in comlist[] *ugh*

Here is the fragment (will compile):
#include <stdlib.h>
#include <stdio.h>

#define MAXNUMOFCOMARGS 4

class comarg {

char *name;
char *usage;

public:
comarg( char*, char*);
int initok() { if(name){ return 1; } else { return -1; } }
void print() { printf( "\t%s\t\"%s\"\n",*&name, *&usage ); }

};

comarg::comarg( char *pname, char *pusage)
{
name = pname;
usage = pusage;
}

static void _regcomargs();
static void _printcomargs(comarg *comlist[]);

// CODE -------------------------------------------

void main()
{
_regcomargs();

printf("Done\n");
}


/*
Register ALL the comarg objects...
*/
void _regcomargs()
{
static comarg *comlist[MAXNUMOFCOMARGS];
comarg *obj;

int counter;
char s[50];

// For now just create a bunch of comargs and stick the pointers in an array

for(counter=0; counter < MAXNUMOFCOMARGS; counter++){

sprintf(s,"Command %d",counter);
obj = new comarg(s,"This command is used to...");

if (obj->initok() != 1){
printf("ERROR: Could not create a new comarg object");
exit ( 0 );
}

comlist[counter]= obj;

}

_printcomargs(comlist);

}


/*
Print every comarg in the array via the member function print();
*/
void _printcomargs(comarg *comlist[])
{

int counter = 0;
comarg *obj;

while(obj = comlist[counter]){
obj->print();
counter++;
}

}

Hurdler
September 5th, 2004, 03:58 AM
If you use C++, you should use the std::string class instead of using "char *" (using "char *" is ok, but std:string is more C++).

The problem you have is because you used a "char *" (and a char []). When you pass "s" to the constructor, the address of s is always the same. With the sprintf, you fill always the same memory area. That's why you have the last string you filled.

What you should do if you want to keep "char *" is to do something like that:comarg::comarg( char *pname, char *pusage)
{
name = strdup(pname); // this allocate a new memory area and copy what is pointed by pname into it
usage = strdup(pusage);
}

// and do not forget to free the memory allocated by strdup()
comarg::~comarg()
{
free(pname);
free(pusage);
}Note you can write the printf() function like that:void print() { printf( "\t%s\t\"%s\"\n",name, usage ); }If you want to use std:string, you have to do more modifcation.

DaniJ
September 6th, 2004, 01:52 PM
That makes sense, I see why it wasn't working now.

So char * is out of fashion now then? I used to use C about 10 years ago and I'm only just remembering stuff now, whilest trying to learn C++. Do you have good link on how to use std::string cause all the stuff I've found so far just looks chinese to me. I need to use it anyway really because soon this class will need to compare user imputed strings with _name and _params.

I'm continuing to work on this class and it's starting to get somewhere near usefull. Here it is so far:

class comarg
{
public:
comarg( char *pname="unnamed", char *pparams= "none", char *pusage= "none") { _size = 1; _name = new char; _params = new char; _usage = new char; create( pname, pparams, pusage); };

~comarg() { free(_name); free(_params); free(_usage); };

void setName (char *name) {_name = name;}
void setParams (char *params) {_params = params;}
void setUsage (char *usage) {_usage = usage;}

int getSize(){ return _size; }

char *getName () { return _name;}
char *getParams () { return _params;}
char *getUsage () { return _usage;}

void print() { printf( "\t%s\t%s\t\"%s\"\n",_name, _params, _usage ); }
void print(comarg *array);

private:
int _size;
char *_name;
char *_params;
char *_usage;

void create( char *pname, char *pparams, char *pusage) { _size++; _name = strdup(pname); _params = strdup(pparams); _usage = strdup(pusage); };

};

// TODO: Make me an inline func
void comarg::print(comarg *array)
{
int temp = _size;
for( ; temp >= 0; temp--){
printf( "\t%s\t%s\t\"%s\"\n",array->_name, array->_params, array->_usage );
array++;
}

}
Now the way it is atm, I can create (and return a pointer) to a either a single or array of comarg objects anywhere, like this:

comarg single = {"-verbose", "", "does stuff"};

or

comarg comlist[] = {
comarg( "-help", "", "displays this command list"),
comarg( "-cfg", "s", "[eg -cfg myfile.cfg] use a custom cfg file"),
comarg( "-out", "s", "[eg -out myfile.out] change the default output file")
};
To allow easy creation of an array of comarg objects.

What I'd like to know is - atm in order to print an array of comarg objects I need to use an overloaded version of print():

comlist->print(comlist);

Surely there must be a better way to write print() so that I don't need to do this. Do I need to use an anchor so I can "step" through?

Hurdler
September 6th, 2004, 02:35 PM
I have no link other than Google. If you want to learn C++ seriously (I mean if you want to do some "advanced" things with it, not simply hacking), I would recommend you to buy Stroustrup's book (where the string class is described).

About your print example, I'm not sure I have understood what you wanted to do. But your example is a bit strange since you pass to the print function the object itself. I suppose comlist->print() should be enough.

DaniJ
September 6th, 2004, 03:39 PM
Doh! I'm stupid, I didn't know you could refer to the current object as this[]. I've rewritten print() to:

void comarg::print()
{
int temp = this->_size;
for( ; temp >= 0; temp--){
if (!this[temp]._name) continue;
printf( "\t%s\t%s\t\"%s\"\n",this[temp]._name, this[temp]._params, this[temp]._usage );
}
}

So now you can use either:

comlist->print();
To print however many comarg objects comlist contains, or you can:

comlist[1].print();
To print a specific comarg object in comlist.

I think I'll pick up a copy of his book, he is the master after all. I want to learn C++ rather than blindly hack things in without understanding how it really works. C++ seems so much more flexible than I remember C used to be.

Pate
September 7th, 2004, 12:55 AM
int temp = this->_size;

Using "this" here is totally unnecessary. Since _size is a class variable, you can refer it directly, like so:

int temp = _size;

Likewise this seems wrong:

this[temp]._name

This has segfault possibilities written all over it. For instance you assume that comarg classess always form an array (which you access with "this") and that you always access them starting from the first element.

Btw using Stroustrup as a first guide to C++ can be quite a confusing experience. It's not very easily accessible.

DaniJ
September 7th, 2004, 05:20 AM
Changed it to int temp = _size, that was totally silly.

Ah. I'll rewrite it as a linked list in that case *spin*

jester
September 11th, 2004, 02:22 AM
Okay, well I finally got the problems sorted out with my program, pretty much. I used a char variable for the input and then std::atoi to convert the variable to an integer, and then I could get the program to check if the input was 1, 2, or 3 and everything worked fine.

I'm trying to convert the damned thing over to using classes now, though. I can get all the teams into classes, that works fine. The only problem I have is getting the menu thing to work in a similar way to the original one. I mean, is there any way your class can include a pointer to a function as one of it's members? So that I can use this pointer to a function like I did in my original program?

Thanks for your help!

smite-meister
September 12th, 2004, 06:40 AM
is there any way your class can include a pointer to a function as one of it's members?
Sure. In C/C++, the class members can be of just any data type.
The only restriction is that the size of the data member must be known at compile time,
which is why you can't use things like

class XXX
{
int n;
char text[n]; // the value of n cannot be known at compile time, so this is an error.
}

On the other hand, this example is perfectly legal:

class XXX
{
typedef int (*function_pointer_t)(char *c); // some shorthand
int n;
char *text;
function_pointer_t fp;
public:
// constructor
XXX(char *message, function_pointer_t func)
{
fp = func;
n = fp(message) + 1; // leave room for the NUL character ending the c-string
text = new char[n];
strncpy(text, message, n);
};
};

and you could use is like this, for example:

int main()
{
XXX temp("some text", strlen);
// now temp.n should be 10 and temp.text should point to a copy of the string.
...
}

Okay, the use of the function pointer is pretty superfluous here, but you get the idea...

jester
September 13th, 2004, 07:20 AM
Bloody hell, something tells me from that code that you seriously know your stuff!
I'll have to have a mess around with that code. Basically what I want it do is so that you have a bunch of functions, like in my original program, and then you can access each one just by putting in a different integer. Or hang on, maybe I'm being a retard here.. even if I use your method, I'm still gonna have to use an array, right?

So the menu thing will be an array of class objects, instead of structures, with the class objects having inside them a bit of text and a function pointer, right? I'm just trying to find the most efficient way of remaking my original program.

Another question..

If you want to convert an int to a std::string, how do you go about doing this? I tried something using a C typecast like:

int a = 99;
stdstring b = (std::string) a;

Didn't work.

Okay, cheers for any help, much appreciated.

Hurdler
September 13th, 2004, 09:08 AM
I hope smite-meister know his stuff :) Imagine the C++ version if he didn't ! ;)

DaniJ
October 28th, 2004, 02:28 AM
Dead simple question:

EDIT: Nevermind... DAMN IM STUPID! *flip* Sussed it!

EDIT 2: Sorry for the bump.

MR_ROCKET
October 28th, 2004, 03:48 PM
/me throws zombie skinz at dani - waaahtah ooah

:P