Archived

This topic is now archived and is closed to further replies.

Classes - making objects 'global'

This topic is 6023 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I''m very new to C++, coming from a BASIC background. I''m interested in using a class to hold vertex data for an OpenGL program. However, it won''t work unless it is possible to define objects in one function and use them elsewhere. Can this be done? My compiler tells me not. Here''s what I''m trying to do (simplififed): class Person { public: char name; int age; }; void Init(void) { Person Fred; Fred.age = 20; } int Main(void) { int a = Fred.age } This gives me a "Fred not defined" error in Main(). How can I declare the Fred object in Init() or any other function but still use him in Main? Rottbott

Share this post


Link to post
Share on other sites
class Person
{
public:
char name;
int age;
};


Fred* Init(void)
{
Person* Fred = new Person();
Fred->age = 20;

return Fred;
}

int Main(void)
{
Person* Fred = Init();
int a = Fred->age;
}

Share this post


Link to post
Share on other sites
Hehe this message board doesnt have C++ code check;

Its supposed to be:

Person* Init() {
Person* Fred = new Person();
Fred->age = 20;
return Fred;
}

void Main() {
Person* Fred = Init();
int a = Fred->age;

delete Fred;
}

Share this post


Link to post
Share on other sites
1. Your Init function isnt really necessary, just use a constructor...

    
class Person
{
public:
Person(int personAge = 20) // Constructor. Age is set to 20 unless otherwise specified.

{
age = personAge;
}
char name;
int age;
};

int Main(void)
{
Person Fred; // Use default age of 20

Person Boris(25) // specify age 25

int a = Fred.age;
int b = Boris.age;
}



2. If you really want global objects, declare them outside of a function like this...
  
// in header file....


extern Person Fred; // fred is available to any function provided this header is included

static Person Nigel; // nigel is only available to the functions defined in this header.


// note that these declarations dont instantiate

// Fred and Nigel, they just make them visible to other files


// in cpp file


Person Fred(23); // Instantiate Fred

Person Nigel(11); // Instantiate Nigel





Edited by - Sandman on June 22, 2001 2:48:49 PM

Share this post


Link to post
Share on other sites
Thanks for the replies, but I think I made myself unclear. I know how to use constructors to specify default values etc, but that''s not really what I''m after. I want to be able to create Fred or Boris anywhere in my code, _without warning_, and be able to access him from elsewhere. I tried using ''extern'' but it didn''t work...


If it helps, what I''m actually doing is trying to use a class to hold vertex data like so:


class Triangle {
public:
float VertexX[3];
float VertexY[3];
float VertexZ[3];
};


I then want to create and destroy Triangles at different points in my code, and process each Triangle for rendering in a Display() function. However, when I create a new Triangle they end up being local to the function that created them.


Rottbott

Share this post


Link to post
Share on other sites
If i indeed correct what you need to do is:

FILE: person.h
  
class Person
{
public:
char name;
int age;
};

// global objects

extern Person Fred;

// global functions prototype

void Init (void);


FILE: person.cpp
  
#include "person.h"

Person Fred; // important (only write this in one source file)


void Init (void)
{
Fred.age = 20;
}


FILE: other.cpp
  
#include "person.h"

int main (int argc, char **argv)
{
int a = Fred.age;
}

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
You can''t really declare global data from within a function. What''s usually done is to create the object with ''new'' and maintain a pointer to it. This object will remain in memory until you explicitly destroy it with ''delete''.

for example:

Person* CreatePerson()
{

Share this post


Link to post
Share on other sites
jpastor, thanks for the explanation but the thing is I don''t know how many ''people'' I want in my program. I''ll be reading data from a file which will tell me which ''people'' to make.

Anon, the pointer thing - I''ll try that.

It may be I''m going about this completely the wrong way.

Thanks for all your replies.


Rottbott

Share this post


Link to post
Share on other sites
er... ok, that wasn''t exactly the most gracefull first post ever :/ (I''m the previous annonymous poster)

Is there a reason tab doesn''t work in text editing on a forum devoted to programming? Or am I just being silly?

Back to the topic:

Create the objects with ''new'' and maintain a pointer to it. You might want to keep the pointers in a global repository like a linked list or something to help keep track of them.

If you don''t keep track of your pointers, you''ll end up causing memory leaks, so remember to explicitly ''destroy'' all the objects you create with ''new'' when you''re done with them.

Share this post


Link to post
Share on other sites
I''ve decided to store pointers in an array of ''unsigned int'' (hopet this is allowed). Now how do I access the object again FROM a pointer? (Sorry if this has already been covered, I''ve not used pointers before today!).


Rottbott

Share this post


Link to post
Share on other sites
First off, you can declare an array of object pointers just like any other data type. Therefore you don''t need to make them unsigned int.

class Person()
{
stuff
more stuff
};

Person* PersonArray[20];

void main()
{
...
}

When referencing an object from a pointer just use ''->'' instead of ''.''.

pBob->name = "Bob Onanob\n"

instead of

Neil.name = "Neil N. Bob\n"


Id reccomend using a linked list instead of an array. But since you''re new to pointers go ahead, just be carefull not to make more objects than the array can hold.

Share this post


Link to post
Share on other sites
Ah, it''s beginning to make some sense now.

Linked lists - I will one day, but I''d like to tackle one new thing at a time as I learn .

Couple of things to clear up:

1) " pBob->name = "Bob Onanob\n" "

Shouldn''t that be *pBob rather than just pBob?


2) How do I assign the address to the pointer? I thought it was this but it doesn''t work:

PersonArray[1] = &Bob;


Rottbott

Share this post


Link to post
Share on other sites
Wait, I realised what I was doing for number 2. I was doing *PersonArray[1] instead of just PersonArray[1]

Now I just have to work out how to access Bob from elsewhere via the pointer which I have (hopefully) stored.

Another worry, will I have to do some clearing up to prevent memory leaks doing this? If so, how?

Thanks for all the help so far, you guys are great :D


Rottbott

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
quote:
Original post by Rottbott
1) " pBob->name = "Bob Onanob\n" "
Shouldn''t that be *pBob rather than just pBob?


No. The -> resolves the indirection for you.

quote:

2) How do I assign the address to the pointer? I thought it was this but it doesn''t work:

PersonArray[1] = &Bob;
Rottbott


Assuming Bob is not a pointer (Declared: "Person Bob"), that should work. If bob is declares as a pointer ("Person *Bob") then the ''&'' operator is not used.

Here''s a quick example:


#include
#include
using namespace std;

class Person
{
public:
string Name;
};

Person* PersonArray[10];

void main()
{
Person* pBob = new Person;

pBob->Name = "Bob Onanob";


PersonArray[1] = pBob;

cout << "Name: " << PersonArray[1]->Name << endl;
}

/*
void main()
{
PersonArray[1] = new Person;
PersonArray[1]->Name = "Bob Onanob";

cout << "Name: " << PersonArray[1]->Name << endl;
}
*/


Either of these will work. The second main() function does the same thing just skips the ''pBob'' middleman.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
To access Bob just do

Personage = Bob->age

The "->" takes care of the *Bob part (e.g. think of Bob->age as *Bob.age, the last one isn''t legitamite code).

As for memory leaks remember the rule that anything you ''new'' you must ''delete''. So somewhere in the program have

delte Bob, or

for (int i=0; i delte PeopleArray;

I don''t know what you''re working under (MFC, Windows API etc...) but if you''re using Windows API you can just delete functions in the WM_DESTROY message.

Hope my code doesn''t have any mistakes!

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
To access Bob just do

Personage = Bob->age

The "->" takes care of the *Bob part (e.g. think of Bob->age as *Bob.age, the last one isn''t legitamite code).

As for memory leaks remember the rule that anything you ''new'' you must ''delete''. So somewhere in the program have

delte Bob, or

for (int i=0; i delte PeopleArray;

I don''t know what you''re working under (MFC, Windows API etc...) but if you''re using Windows API you can just delete functions in the WM_DESTROY message.

Hope my code doesn''t have any mistakes! BTW what project are you doing?

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
To access Bob just do

Personage = Bob->age

The "->" takes care of the *Bob part (e.g. think of Bob->age as *Bob.age, the last one isn''t legitamite code).

As for memory leaks remember the rule that anything you ''new'' you must ''delete''. So somewhere in the program have

delte Bob, or

for (int i=0; i delte PeopleArray;

I don''t know what you''re working under (MFC, Windows API etc...) but if you''re using Windows API you can just delete functions in the WM_DESTROY message.

Hope my code doesn''t have any mistakes! BTW what project is this for?

Share this post


Link to post
Share on other sites
Hmmm...anon again.

Right, using that code the assigning part works, HOWEVER, when I try to use the pointer array (which I defined when I defined the class at the top of my code) in another function, it says it hasn't been created in that function. Any ideas?

EDIT - Now I feel stupid. I mispelled it. Sorry to bother you there. Well, now my code compiles. Off to run it. By the way, what must I do in the way of clearing up after using it like this?

Edited by - Rottbott on June 22, 2001 5:54:41 PM

Share this post


Link to post
Share on other sites
All right! All appears to work beautifully!

Thanks very much to everyone who replied, my C++ knowledge has been extended plenty today. Now I''d better go, this thread is starting to account for a sizeable fraction of the total posts on this board

*Signs out*

Share this post


Link to post
Share on other sites
quote:
Original post by Rottbott
Hmmm...anon again.

Right, using that code the assigning part works, HOWEVER, when I try to use the pointer array (which I defined when I defined the class at the top of my code) in another function, it says it hasn''t been created in that function. Any ideas?


Rottbott




#include "string"
#include "iostream"
using namespace std;

class Person
{
public:
string Name;
};

Person* PersonArray[10];

void SetName( void );


void main()
{
PersonArray[1] = new Person;

SetName();

cout << "Name: " << PersonArray[1]->Name << endl;
}

void SetName( void )
{
PersonArray[1]->Name = "Bob Onanob";
}



Is this what you mean? Is the function in a different source file? If so you need to declare the array as "extern Person* PersonArray[10]" in the other file.

Share this post


Link to post
Share on other sites