Thread: instance of a class disappearing after function ends

  1. #1
    Registered User combatdave's Avatar
    Join Date
    Nov 2005
    Posts
    20

    instance of a class disappearing after function ends

    i know that this is a simple question, and i know that theres a simple answer, but for the life of me i cant remember how to do it. basically, i have a class (called AgentClass), and as im using a graphics library called GameX there is a function called on startup called GameInit. In this function goes all initialisation code, including where i am attempting to make a whole bunch of instances of my AgentClass class. i have a linked list type thingy in place to cycle through them all, and the pointers for this are all working fine (i have several instances created outside any function which work fine).

    Basically, any instance of my class created in this function disappears as soon as the function returns. I have checked this by putting a little thing in the deconstructor which lets me know when the instance is removed - and they are being deleted at the end of the function.

    currently to create an instance i do:

    Code:
    AgentClass myAgent(100,100,...other params...);
    so... what do i do to stop them disappearing after the function returns?

    thanks so much for any help, i know this is an easy question...
    ( )

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You can create the object before calling the function, and then pass the object to the function by reference.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Reverse Engineer maxorator's Avatar
    Join Date
    Aug 2005
    Location
    Estonia
    Posts
    2,318
    If you declare your class variable inside your class, then you can't use it elsewhere anyway.
    So if you only need it to stay in that function till the program ends, use static.
    "The Internet treats censorship as damage and routes around it." - John Gilmore

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Oh, I read it again, and realised my mistake: you are specifically creating the objects in this function. What I wrote does not apply.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    "Why use dynamic memory?"
    Join Date
    Aug 2006
    Posts
    186
    every thing in function will end as the functions end
    "C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do, it blows away your whole leg."-Bjarne Stroustrup
    Nearing the end of finishing my 2D card game! I have to work on its 'manifesto' though <_<

  6. #6
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    You need to create them on the heap with new. Don't forget to delete them in GameDeinit().
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  7. #7
    Reverse Engineer maxorator's Avatar
    Join Date
    Aug 2005
    Location
    Estonia
    Posts
    2,318
    Statics are good...
    Code:
    #include<iostream>
    class Fruit{
    	public:
    		int size;
    		Fruit();
    };
    Fruit::Fruit(){
    	size=0;
    }
    int FruitSize(){
    	static Fruit apple;
    	if(apple.size==0){
    		printf("The apple was not loaded, loading.\n");
    		apple.size=1;
    	}
    	else{
    		printf("The apple is already loaded.\n");
    	}
    }
    int main(){
    	FruitSize();
    	FruitSize();
    	FruitSize();
    	FruitSize();
    	std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    }
    "The Internet treats censorship as damage and routes around it." - John Gilmore

  8. #8
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    But not in this case. If GameInit() is supposed to set up the data for the entire game, then it really shouldn't keep that data as statics. It would actually be more appropriate to make it global, then.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  9. #9
    Registered User combatdave's Avatar
    Join Date
    Nov 2005
    Posts
    20
    cheers for all the replies, nice to have such an active forum...

    creating them on the heap, i assume that gives me pointers to the location? i can deal with that. then i have to make sure to free all the memory at the end, right?

    isnt there an easier way to do this? im sure ive done it once before - created lots of objects in a given function which can then be accessed anywhere else in the program - but i cant remember how. maybe i was allocating each of them memory...

    i think cornedbee is onto it - can global be used from inside a function?
    ( )

  10. #10
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >can global be used from inside a function?
    Unless you hide it with a local variable of the same name, yes.
    My best code is written with the delete key.

  11. #11
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Quote Originally Posted by Prelude
    >can global be used from inside a function?
    Unless you hide it with a local variable of the same name, yes.
    Can't you still use :: to access the global and differentiate it from the local?

    Code:
    int x = 0;  // Global
    
    void foo()
    {
        int x = 5;  // Local
    
        cout << "Local x: " << x << endl;
        cout << "Global x: " << ::x << endl;
    }
    Thought you could do that.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  12. #12
    Registered User combatdave's Avatar
    Join Date
    Nov 2005
    Posts
    20
    can a global be declared from inside a function, though? sorry i probably should have said it more clearly to start with...
    ( )

  13. #13
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Quote Originally Posted by combatdave
    can a global be declared from inside a function, though? sorry i probably should have said it more clearly to start with...
    The global can be referenced from within a function, but it cannot be declared inside the function... that would make it a local variable (local to the function in question) and not global.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    I considered suggesting some kind of singleton to which you can add AgentClass objects in GameInit(), and from which you can remove them, but that design may not be very good. CornedBee's suggestion sounds simpler though, but can you just return a pointer from GameInit(), or change its signature (e.g., pass a pointer by reference)?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  15. #15
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Urgh!

    Meh. Pass a reference to the GameState object that contains everything the game needs as members.

    Better yet, just instantiate the GameState object and replace GameInit with GameState's constructor. Replace GameDeinit() with the destructor. Create a single GameInit instance in WinMain/main and let C++ handle the rest.
    Init/Deinit function pairs are sooo C.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointer to a class inside the WindowsProcedure function
    By like_no_other in forum Windows Programming
    Replies: 3
    Last Post: 06-01-2009, 12:52 PM
  2. Callback function as class method
    By schifers in forum Windows Programming
    Replies: 39
    Last Post: 05-19-2008, 03:02 PM
  3. Class function pointers
    By VirtualAce in forum C++ Programming
    Replies: 40
    Last Post: 02-17-2005, 12:55 AM
  4. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM
  5. Class function that returns the instance it's called from
    By L Boksha in forum C++ Programming
    Replies: 4
    Last Post: 05-25-2002, 11:52 AM