Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Class initialization and memory allocation

Class initialization and memory allocation

Scheduled Pinned Locked Moved C / C++ / MFC
csharpc++performancequestionlearning
19 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • C Christian Flutcher

    #include <iostream.h>
    class Person
    {
    string name;
    int age;
    public:
    string GetName(void);
    int GetAge(void);
    Person(string personName,int personAge);
    Person(void);
    };

    int main()
    {
    Person *person = new Person("Chris",30);
    cout << person->GetName() << endl;
    cout << person->GetAge() << endl;

        **Person anotherPerson**;
        cout << anotherPerson.GetName() << endl;
        cout << anotherPerson.GetAge() << endl;
    
        delete person;
        return 0;
    

    }

    string Person::GetName()
    {
    return name;
    }
    int Person::GetAge()
    {
    return age;
    }
    Person::Person(string personName,int personAge)
    {
    name = personName;
    age = personAge;
    }
    Person::Person()
    {
    name = "Unknown";
    age = 0;
    }

    I used to program using C# and learning C++ now. I have some doubts on the above shown program. 1 - Person anotherPerson is declared but not initialized. But still calls to anotherPerson.GetName() worked. How this is happening? 2 - Is there any difference when allocating memory for *person and anotherPerson? 3 - I know we should delete the pointer variables to claim memory. But AFAIK, there is no need to delete the anotherPerson variable. How it gets removed from memory?

    _ Offline
    _ Offline
    _AnsHUMAN_
    wrote on last edited by
    #2

    Christian Flutcher wrote:

    1 - Person anotherPerson is declared but not initialized. But still calls to anotherPerson.GetName() worked. How this is happening?

    The compiler provides a default constructor for the class. So when you create an object for the class the default constructor gets invoked and the object is initialized.

    Christian Flutcher wrote:

    2 - Is there any difference when allocating memory for *person and anotherPerson?

    Yes. The memory is allocated from heap in case you use new (ie *person), otherwise it is allocated from stack.

    Christian Flutcher wrote:

    3 - I know we should delete the pointer variables to claim memory. But AFAIK, there is no need to delete the anotherPerson variable. How it gets removed from memory?

    The memory allocated is returned to the stack once the object goes out of scope

    Somethings seem HARD to do, until we know how to do them. ;-)_AnShUmAn_

    modified on Friday, September 5, 2008 1:33 AM

    C 1 Reply Last reply
    0
    • C Christian Flutcher

      #include <iostream.h>
      class Person
      {
      string name;
      int age;
      public:
      string GetName(void);
      int GetAge(void);
      Person(string personName,int personAge);
      Person(void);
      };

      int main()
      {
      Person *person = new Person("Chris",30);
      cout << person->GetName() << endl;
      cout << person->GetAge() << endl;

          **Person anotherPerson**;
          cout << anotherPerson.GetName() << endl;
          cout << anotherPerson.GetAge() << endl;
      
          delete person;
          return 0;
      

      }

      string Person::GetName()
      {
      return name;
      }
      int Person::GetAge()
      {
      return age;
      }
      Person::Person(string personName,int personAge)
      {
      name = personName;
      age = personAge;
      }
      Person::Person()
      {
      name = "Unknown";
      age = 0;
      }

      I used to program using C# and learning C++ now. I have some doubts on the above shown program. 1 - Person anotherPerson is declared but not initialized. But still calls to anotherPerson.GetName() worked. How this is happening? 2 - Is there any difference when allocating memory for *person and anotherPerson? 3 - I know we should delete the pointer variables to claim memory. But AFAIK, there is no need to delete the anotherPerson variable. How it gets removed from memory?

      S Offline
      S Offline
      santhoshv84
      wrote on last edited by
      #3

      Hi, 1. In Person anotherPerson, nothing is initialized then it will get Person::Person() constructor. So 'Unknown' will be the name and '0' will be the age. 2. you may be knowing about the difference between *person and anotherPerson is References vs. Pointers.

      The price of anything is the amount of life you exchange for it. Thanks and Regards. SANTHOSH V

      C 1 Reply Last reply
      0
      • _ _AnsHUMAN_

        Christian Flutcher wrote:

        1 - Person anotherPerson is declared but not initialized. But still calls to anotherPerson.GetName() worked. How this is happening?

        The compiler provides a default constructor for the class. So when you create an object for the class the default constructor gets invoked and the object is initialized.

        Christian Flutcher wrote:

        2 - Is there any difference when allocating memory for *person and anotherPerson?

        Yes. The memory is allocated from heap in case you use new (ie *person), otherwise it is allocated from stack.

        Christian Flutcher wrote:

        3 - I know we should delete the pointer variables to claim memory. But AFAIK, there is no need to delete the anotherPerson variable. How it gets removed from memory?

        The memory allocated is returned to the stack once the object goes out of scope

        Somethings seem HARD to do, until we know how to do them. ;-)_AnShUmAn_

        modified on Friday, September 5, 2008 1:33 AM

        C Offline
        C Offline
        Christian Flutcher
        wrote on last edited by
        #4

        Thanks :)

        _AnShUmAn_ wrote:

        Yes. The memory is allocated from heap in case you use new (ie *person), otherwise it is allocated from stack.

        Well, so which one is the recommended practice? use pointer variables always and delete after usage or use the normal one which goes to stack?

        C _ R 3 Replies Last reply
        0
        • S santhoshv84

          Hi, 1. In Person anotherPerson, nothing is initialized then it will get Person::Person() constructor. So 'Unknown' will be the name and '0' will be the age. 2. you may be knowing about the difference between *person and anotherPerson is References vs. Pointers.

          The price of anything is the amount of life you exchange for it. Thanks and Regards. SANTHOSH V

          C Offline
          C Offline
          Christian Flutcher
          wrote on last edited by
          #5

          Thank you santhosh. Your help is much appreciated.

          1 Reply Last reply
          0
          • C Christian Flutcher

            Thanks :)

            _AnShUmAn_ wrote:

            Yes. The memory is allocated from heap in case you use new (ie *person), otherwise it is allocated from stack.

            Well, so which one is the recommended practice? use pointer variables always and delete after usage or use the normal one which goes to stack?

            C Offline
            C Offline
            Cedric Moonen
            wrote on last edited by
            #6

            Depends really of the situation, sometimes you will need to use pointers so you don't have a choice. I tend to prefer using variables on the stack rather than on the heap when I can. Allocating/deallocating a lot of variables on the heap can lead to memory fragmentation which can be an issue if you tend to do it a lot. Furthermore, the cost (in time) of creating an object on the heap is a bit higher than creating an object on the stack.

            Cédric Moonen Software developer
            Charting control [v1.5] OpenGL game tutorial in C++

            C 1 Reply Last reply
            0
            • C Christian Flutcher

              Thanks :)

              _AnShUmAn_ wrote:

              Yes. The memory is allocated from heap in case you use new (ie *person), otherwise it is allocated from stack.

              Well, so which one is the recommended practice? use pointer variables always and delete after usage or use the normal one which goes to stack?

              _ Offline
              _ Offline
              _AnsHUMAN_
              wrote on last edited by
              #7

              The stack is where memory is allocated for automatic variables within functions. The memory allocated in the stack area is used and reused during program execution. It should be clear that memory allocated in this area will contain garbage values left over from previous usage. The heap segment provides more stable storage of data for a program; memory allocated in the heap remains in existence for the duration of a program. Therefore, global variables (storage class external), and static variables are allocated on the heap. The memory allocated in the heap area, if initialized to zero at program start, remains zero until the program makes use of it. Thus, the heap area need not contain garbage.

              Somethings seem HARD to do, until we know how to do them. ;-)_AnShUmAn_

              R N 2 Replies Last reply
              0
              • C Christian Flutcher

                Thanks :)

                _AnShUmAn_ wrote:

                Yes. The memory is allocated from heap in case you use new (ie *person), otherwise it is allocated from stack.

                Well, so which one is the recommended practice? use pointer variables always and delete after usage or use the normal one which goes to stack?

                R Offline
                R Offline
                Rajesh R Subramanian
                wrote on last edited by
                #8

                Christian Flutcher wrote:

                Well, so which one is the recommended practice? use pointer variables always and delete after usage or use the normal one which goes to stack?

                Generally, it is advisable to use the stack as much as possible. At the same time, you should also know that the stack would not have very large and if you go on "pushing" data into the stack, that might result in a Stack overflow[^], which would kill your program. The heap, on the other hand is comparatively large and can be used to store huge variables, can be used when the memory allocated should not be cleaned up even if the variable goes out of scope (you will need to clean it up). You don't clean it up and the memory can go fragmented over a period of time. If this happens, your program will suffer from a serious performance degradation. There is way much more for typing in a message, Google for "Stack vs Heap" and you'll get to read loads of interesting stuff. :) See here as well: http://www.gotw.ca/gotw/009.htm[^]

                Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal - Friedrich Nietzsche .·´¯`·->Rajesh<-·´¯`·. [Microsoft MVP - Visual C++]

                C 1 Reply Last reply
                0
                • _ _AnsHUMAN_

                  The stack is where memory is allocated for automatic variables within functions. The memory allocated in the stack area is used and reused during program execution. It should be clear that memory allocated in this area will contain garbage values left over from previous usage. The heap segment provides more stable storage of data for a program; memory allocated in the heap remains in existence for the duration of a program. Therefore, global variables (storage class external), and static variables are allocated on the heap. The memory allocated in the heap area, if initialized to zero at program start, remains zero until the program makes use of it. Thus, the heap area need not contain garbage.

                  Somethings seem HARD to do, until we know how to do them. ;-)_AnShUmAn_

                  R Offline
                  R Offline
                  Rajesh R Subramanian
                  wrote on last edited by
                  #9

                  _AnShUmAn_ wrote:

                  It should be clear that memory allocated in this area will contain garbage values left over from previous usage.

                  Correct me if I'm wrong, this may be true in case of Windows, but not for all other OS. That was my experience with Solaris, at least.

                  Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal - Friedrich Nietzsche .·´¯`·->Rajesh<-·´¯`·. [Microsoft MVP - Visual C++]

                  _ 1 Reply Last reply
                  0
                  • R Rajesh R Subramanian

                    Christian Flutcher wrote:

                    Well, so which one is the recommended practice? use pointer variables always and delete after usage or use the normal one which goes to stack?

                    Generally, it is advisable to use the stack as much as possible. At the same time, you should also know that the stack would not have very large and if you go on "pushing" data into the stack, that might result in a Stack overflow[^], which would kill your program. The heap, on the other hand is comparatively large and can be used to store huge variables, can be used when the memory allocated should not be cleaned up even if the variable goes out of scope (you will need to clean it up). You don't clean it up and the memory can go fragmented over a period of time. If this happens, your program will suffer from a serious performance degradation. There is way much more for typing in a message, Google for "Stack vs Heap" and you'll get to read loads of interesting stuff. :) See here as well: http://www.gotw.ca/gotw/009.htm[^]

                    Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal - Friedrich Nietzsche .·´¯`·->Rajesh<-·´¯`·. [Microsoft MVP - Visual C++]

                    C Offline
                    C Offline
                    Christian Flutcher
                    wrote on last edited by
                    #10

                    Rajesh, Nice to see your reply. As you said all pointers are created on heap and others are on stack. Consider the following one

                    Person person; // On stack
                    Person *personPointer = &person; // Where this will go?

                    R C 2 Replies Last reply
                    0
                    • C Cedric Moonen

                      Depends really of the situation, sometimes you will need to use pointers so you don't have a choice. I tend to prefer using variables on the stack rather than on the heap when I can. Allocating/deallocating a lot of variables on the heap can lead to memory fragmentation which can be an issue if you tend to do it a lot. Furthermore, the cost (in time) of creating an object on the heap is a bit higher than creating an object on the stack.

                      Cédric Moonen Software developer
                      Charting control [v1.5] OpenGL game tutorial in C++

                      C Offline
                      C Offline
                      Christian Flutcher
                      wrote on last edited by
                      #11

                      Cedric Moonen wrote:

                      Allocating/deallocating a lot of variables on the heap can lead to memory fragmentation which can be an issue if you tend to do it a lot

                      Are there any rules which should be considered when instantiating objects? How do you decide where the object should go? I am bit confused :confused:

                      C 1 Reply Last reply
                      0
                      • _ _AnsHUMAN_

                        The stack is where memory is allocated for automatic variables within functions. The memory allocated in the stack area is used and reused during program execution. It should be clear that memory allocated in this area will contain garbage values left over from previous usage. The heap segment provides more stable storage of data for a program; memory allocated in the heap remains in existence for the duration of a program. Therefore, global variables (storage class external), and static variables are allocated on the heap. The memory allocated in the heap area, if initialized to zero at program start, remains zero until the program makes use of it. Thus, the heap area need not contain garbage.

                        Somethings seem HARD to do, until we know how to do them. ;-)_AnShUmAn_

                        N Offline
                        N Offline
                        Naveen
                        wrote on last edited by
                        #12

                        _AnShUmAn_ wrote:

                        Therefore, global variables (storage class external), and static variables are allocated on the heap

                        A small correction. They are actually store in the .data section or .rdata section of the applications.

                        nave [OpenedFileFinder] [My Blog]

                        1 Reply Last reply
                        0
                        • C Christian Flutcher

                          Rajesh, Nice to see your reply. As you said all pointers are created on heap and others are on stack. Consider the following one

                          Person person; // On stack
                          Person *personPointer = &person; // Where this will go?

                          C Offline
                          C Offline
                          Cedric Moonen
                          wrote on last edited by
                          #13

                          The pointer itself is on the stack but it contains the address of another variable. This address can either be in stack or in heap (it depends where you allocated it). Don't forget that pointers are variables too (they simply contain an address).

                          Cédric Moonen Software developer
                          Charting control [v1.5] OpenGL game tutorial in C++

                          1 Reply Last reply
                          0
                          • C Christian Flutcher

                            Rajesh, Nice to see your reply. As you said all pointers are created on heap and others are on stack. Consider the following one

                            Person person; // On stack
                            Person *personPointer = &person; // Where this will go?

                            R Offline
                            R Offline
                            Rajesh R Subramanian
                            wrote on last edited by
                            #14

                            Christian Flutcher wrote:

                            As you said all pointers are created on heap and others are on stack

                            Please, don't accuse me of saying such a thing. I never said it. Heap memory will be allocated whenever you use the new operator for allocating memory or whenever you use dynamic memory allocation functions like malloc(), calloc(), etc., :)

                            Christian Flutcher wrote:

                            Person *personPointer = &person; // Where this will go?

                            Will be on the stack. :)

                            Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal - Friedrich Nietzsche .·´¯`·->Rajesh<-·´¯`·. [Microsoft MVP - Visual C++]

                            C 1 Reply Last reply
                            0
                            • C Christian Flutcher

                              Cedric Moonen wrote:

                              Allocating/deallocating a lot of variables on the heap can lead to memory fragmentation which can be an issue if you tend to do it a lot

                              Are there any rules which should be considered when instantiating objects? How do you decide where the object should go? I am bit confused :confused:

                              C Offline
                              C Offline
                              Cedric Moonen
                              wrote on last edited by
                              #15

                              No, there's no rule for this but in most of the cases, it's not a big problem if you allocate a variable on the heap or on the stack. One point to remember is that variables on the stack will be destroyed when they go out of scope. So, if you have a variable which is local to a function, this variable will be destroyed when the function exits. Or if you want a simple rule: try to allocate variables on the stack when you can.

                              Cédric Moonen Software developer
                              Charting control [v1.5] OpenGL game tutorial in C++

                              C 1 Reply Last reply
                              0
                              • C Cedric Moonen

                                No, there's no rule for this but in most of the cases, it's not a big problem if you allocate a variable on the heap or on the stack. One point to remember is that variables on the stack will be destroyed when they go out of scope. So, if you have a variable which is local to a function, this variable will be destroyed when the function exits. Or if you want a simple rule: try to allocate variables on the stack when you can.

                                Cédric Moonen Software developer
                                Charting control [v1.5] OpenGL game tutorial in C++

                                C Offline
                                C Offline
                                Christian Flutcher
                                wrote on last edited by
                                #16

                                Thanks Cedric. Your help is much appreciated.

                                1 Reply Last reply
                                0
                                • R Rajesh R Subramanian

                                  _AnShUmAn_ wrote:

                                  It should be clear that memory allocated in this area will contain garbage values left over from previous usage.

                                  Correct me if I'm wrong, this may be true in case of Windows, but not for all other OS. That was my experience with Solaris, at least.

                                  Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal - Friedrich Nietzsche .·´¯`·->Rajesh<-·´¯`·. [Microsoft MVP - Visual C++]

                                  _ Offline
                                  _ Offline
                                  _AnsHUMAN_
                                  wrote on last edited by
                                  #17

                                  I have never worked on Solaris platform but as for as windows is concerned this is correct

                                  Somethings seem HARD to do, until we know how to do them. ;-)_AnShUmAn_

                                  1 Reply Last reply
                                  0
                                  • R Rajesh R Subramanian

                                    Christian Flutcher wrote:

                                    As you said all pointers are created on heap and others are on stack

                                    Please, don't accuse me of saying such a thing. I never said it. Heap memory will be allocated whenever you use the new operator for allocating memory or whenever you use dynamic memory allocation functions like malloc(), calloc(), etc., :)

                                    Christian Flutcher wrote:

                                    Person *personPointer = &person; // Where this will go?

                                    Will be on the stack. :)

                                    Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal - Friedrich Nietzsche .·´¯`·->Rajesh<-·´¯`·. [Microsoft MVP - Visual C++]

                                    C Offline
                                    C Offline
                                    Christian Flutcher
                                    wrote on last edited by
                                    #18

                                    Oops It was not you. My appologies.

                                    R 1 Reply Last reply
                                    0
                                    • C Christian Flutcher

                                      Oops It was not you. My appologies.

                                      R Offline
                                      R Offline
                                      Rajesh R Subramanian
                                      wrote on last edited by
                                      #19

                                      No need to apologize, I was just kidding. :)

                                      Many are stubborn in pursuit of the path they have chosen, few in pursuit of the goal - Friedrich Nietzsche .·´¯`·->Rajesh<-·´¯`·. [Microsoft MVP - Visual C++]

                                      1 Reply Last reply
                                      0
                                      Reply
                                      • Reply as topic
                                      Log in to reply
                                      • Oldest to Newest
                                      • Newest to Oldest
                                      • Most Votes


                                      • Login

                                      • Don't have an account? Register

                                      • Login or register to search.
                                      • First post
                                        Last post
                                      0
                                      • Categories
                                      • Recent
                                      • Tags
                                      • Popular
                                      • World
                                      • Users
                                      • Groups