variables in instances of a class

This is a discussion on variables in instances of a class within the C++ Programming forums, part of the General Programming Boards category; Hi. I want to learn about how classes are allocated in memory. Is there an instance of each function for ...

  1. #1
    alloc(MEM_NEWBIE)
    Guest

    variables in instances of a class

    Hi. I want to learn about how classes are allocated in memory. Is there an instance of each function for every instance of the class? That would seem pretty wasteful to me. For instance:

    //if class 'ThisClass' had a function like this..
    ThisClass::ThisFunc()
    {
    int ANumber;
    }


    //And then i had several instances of it...
    ThisClass MyClass[10];

    Is there memory allocated for 'ANumber' 10 times? How does this all work? How are functions stored in memory? If i saved my class to a file what would happen? It would just be the pointers to the functions location in memory at the time it was saved that were stored right (as well as variables in th class)?

    fwrite(&MyClass[0], ...

    ???

    Thank you for your help.

  2. #2
    Evil Member
    Join Date
    Jan 2002
    Posts
    638
    Every instance of a class has it's own data members. If you think of classes as objects, this makes a lot of sense.

    Consider if you had an array of ten ints. It would obviously be necesary for each int to have it's own memory allocated, so each could be unique. The same goes for a class' data members. As for functions, non-virtual function are replicated in instaces of a class, but the overhead this imposes is minimal. Virtual functions are trickier, there is a some kind of offset table maintained for call to virtual functions.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Declaring SDL_Rect variables in a class?
    By pwnz32 in forum C++ Programming
    Replies: 10
    Last Post: 07-27-2008, 07:12 PM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Need help to build network class
    By weeb0 in forum C++ Programming
    Replies: 0
    Last Post: 02-01-2006, 10:33 AM
  4. multiple instances and variables
    By FOOTOO in forum Windows Programming
    Replies: 1
    Last Post: 04-07-2005, 10:54 AM
  5. Replies: 4
    Last Post: 09-12-2001, 02:05 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21