Thread: array of pointers to objects

  1. #1
    Registered User xion's Avatar
    Join Date
    Jul 2003
    Posts
    63

    array of pointers to objects

    on declaring an array of pointers to objects does the program allocate memory for 100 persons, or only allocates them upon
    Code:
    persPtr[n] = new person;
    ? having a hard time understanding the operator new.
    Code:
    ///////////////////////////////////////
    class person		//class of persons
    {
    protected:
    	char name[40];		//persons name
    public:
    	void setName()		//set the name
    	{
    		cout << "Enter name:  ";
    		cin >> name;
    	}
    	void printName()	//get the name
    	{
    		cout << "\n  Name is:  " << name;
    	}
    };
    ///////////////////////////////////////
    int main()
    {
        person* persPtr[100];    //array of pointers to persons
        int n = 0;                //number of persons in array
        char choice;
    
        do
        {
            persPtr[n] = new person;        //make new object
            persPtr[n]->setName();            //set persons name
            n++;    //count new person
            cout << "Enter another (y/n)? ";    //enter another?
            cin >> choice;
        } while( choice == 'y' );    //quit on 'n'
    
        for(int i = 0; i < n; i++)
        {
            cout << "\nPerson number " << i+1;
            persPtr[i]->printName();
        }
        
        cout << endl;
        return 0;
    }    //end main()
    Last edited by xion; 02-07-2005 at 03:05 PM.

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    In your case, the program first allocates memory for an array of 100 pointers to type person on the stack. The memory for the individual person objects gets allocated (off the heap) only when you call new person in your loop. In your program, the operator new tries to get a contiguous chunk of memory sizeof(person) bytes long and assigns the address of that memory chunk to a particular array element persPtr[n] for n = 0 .. 99.

    Code:
    do
    {
        persPtr[n] = new person;        //make new object
        persPtr[n]->setName();            //set persons name
        n++;    //count new person
        cout << "Enter another (y/n)? ";    //enter another?
        cin >> choice;
    } while( choice == 'y'  && n < 100 );    //quit on 'n'
    Might want to add that just to make sure something bad doesn't happen.
    Last edited by hk_mp5kpdw; 02-07-2005 at 02:15 PM.
    "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

  3. #3
    C/C++ homeyg's Avatar
    Join Date
    Nov 2004
    Location
    Louisiana, USA
    Posts
    209
    When he would want to delete all that memory, he would have to do this, right?

    Code:
    for(int i = 0; i<100; i++)
    {
         delete prsPrt[i];
    }
    Am I right?

  4. #4
    Registered User xion's Avatar
    Join Date
    Jul 2003
    Posts
    63
    thanks for the informative reply. i did some searching on the differences between stack and heap and i just want to make sure i got this right. i edited my first post to include the class person. sizeof(person) returns 40. does that mean 40 bytes are allocated on the heap, and the member functions and its variables of that class is on the stack?

    and on the stack, things are freed automatically where as the heap..the programmer has the power to allocate and is responsible with de-allocating the memory?

  5. #5
    C/C++ homeyg's Avatar
    Join Date
    Nov 2004
    Location
    Louisiana, USA
    Posts
    209
    Quote Originally Posted by xion
    thanks for the informative reply. i did some searching on the differences between stack and heap and i just want to make sure i got this right. i edited my first post to include the class person. sizeof(person) returns 40. does that mean 40 bytes are allocated on the heap, and the member functions and its variables of that class is on the stack?

    and on the stack, things are freed automatically where as the heap..the programmer has the power to allocate and is responsible with de-allocating the memory?
    On the stack, things stay in scope for the duration of the function they're created in, and then they go out of scope. On the the heap, things stay in scope until you delete them. This means that other functions can access them by means of pointers.

  6. #6
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Quote Originally Posted by xion
    does that mean 40 bytes are allocated on the heap, and the member functions and its variables of that class is on the stack?
    Yes, the 40 bytes are allocated on the heap, and your persPtr array likely occupies 400 bytes (assuming 4-byte pointers) on the stack. As for the member functions and their local variables I would have to say for the local variables themselves, yes... they reside on the stack. The functions themselves however reside in an area of memory which I personally would not call the "stack" as is routinely talked about (maybe someone else can correct me or add to this in some way). As an example, let's make a simple test program:


    Code:
    #include <fstream>
    #include <iostream>
    using namespace std;
    
    void func1(void)
    {
        int i;
    
        cout << "Address of local (to func1) variable i: " << &i << endl;
    }
    
    void func2(void)
    {
        int i;
    
        cout << "Address of local (to func2) variable i: " << &i << endl;
        cout << "Address of func1 (called from func2)  : " << func1 << endl;
        cout << "******Calling func1 (from func2)******" << endl;
        func1();
    }
    
    int main()
    {
        int i;
        
        cout << "Address of local (to main) variable i : " << &i << endl;
        cout << "Address of func1 (called from main)   : " << func1 << endl;
        cout << "Address of func2 (called from main)   : " << func2 << endl;
        cout << "******Calling func1 (from main)******" << endl;
        func1();
        cout << "******Calling func2 (from main)******" << endl;
        func2();
        
        return 0;
    }
    Output using MSVC 6.0:
    Code:
    Address of local (to main) variable i : 0012FF7C
    Address of func1 (called from main)   : 0040142E
    Address of func2 (called from main)   : 00401429
    ******Calling func1 (from main)******
    Address of local (to func1) variable i: 0012FF24
    ******Calling func2 (from main)******
    Address of local (to func2) variable i: 0012FF24
    Address of func1 (called from func2)  : 0040142E
    ******Calling func1 (from func2)******
    Address of local (to func1) variable i: 0012FECC
    Of note, the functions always have a fixed address. func1 always has the address of 0040142E and func2 always has the address of 00401429. This indicates to me that their address is fixed in memory regardless of where they are called from. Whether this area of memory can be technically called the stack or not is not something I can say.

    The local variables on the other hand are a different matter. Look especially at the last three lines in green. The local variable i in func1 starts with address 0012FF24. After the function exits, i is popped from the stack and we run func2 where its local variable i reports the exact same address as func1's local i variable did. Now func2 calls func1 before it exits and when this happens, func1's local variable i has a different address then when it was first called on its own outside of func2. You should gather from this that the variables for these functions are therefore pushed/popped on/off the stack.

    Running the same prog on my Visual Studio .Net compiler I get different addresses, but the same general conclusion can be drawn:
    Code:
    Address of local (to main) variable i : 0012F5A0
    Address of func1 (called from main)   : 00404D50
    Address of func2 (called from main)   : 00404DF0
    ******Calling func1 (from main)******
    Address of local (to func1) variable i: 0012F594
    ******Calling func2 (from main)******
    Address of local (to func2) variable i: 0012F594
    Address of func1 (called from func2)  : 00404D50
    ******Calling func1 (from func2)******
    Address of local (to func1) variable i: 0012F588
    Quote Originally Posted by xion
    and on the stack, things are freed automatically where as the heap..the programmer has the power to allocate and is responsible with de-allocating the memory?
    Items on the stack are popped for you (destructors get called where appropriate). This includes the memory allocated for any local pointer variable itself but not the memory the pointer pointed to. This allocated memory must be deallocated by the programmer (unless you are using some type of a smart pointer such as an auto_ptr):

    Code:
    #include <memory>
    #include <iostream>
    
    class obj
    {
    public:
        obj() { std::cout << "Constructor called" << std::endl; }
        ~obj() { std::cout << "Destructor called" << std::endl; }
    };
    
    int main()
    {
        std::auto_ptr<obj> ap(new obj);
    
        // Once ap goes out of scope at end of "main", obj's destructor will be called
    }
    Output:
    Code:
    Constructor called
    Destructor called
    "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

  7. #7
    Registered User xion's Avatar
    Join Date
    Jul 2003
    Posts
    63
    wow. thanks for taking the time to explain ALL that. got it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. MergeSort with array of pointers
    By lionheart in forum C Programming
    Replies: 18
    Last Post: 08-01-2008, 10:23 AM
  2. array of pointers to an array pointers
    By onebrother in forum C Programming
    Replies: 2
    Last Post: 07-28-2008, 11:45 AM
  3. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  4. Creating an array of pointers to int[]
    By OkashiiKen in forum C Programming
    Replies: 3
    Last Post: 09-29-2006, 06:48 PM
  5. Replies: 4
    Last Post: 10-16-2003, 11:26 AM