Thread: Help with line of code

  1. #1
    Registered User
    Join Date
    Nov 2004

    Help with line of code

    Could someone tell me what this like of code means:

    num[1] = new Person("James", 6, 75);
    num[2] = new Person...
    I know what most of it means but what does "new" mean? How do I access the height of a certain person?


  2. #2
    Registered User
    Join Date
    Jan 2005
    new allocates memory and returns a pointer, it is usually used to create a new instance of a class as the code you posted is doing.
    If the class exposes a member variable called height then
    cout << num[0].height;
    You'd need to take a look at the class defination though.

  3. #3
    Registered User
    Join Date
    Nov 2004
    I'm don't really know much about this kind of thing but I think its a new Struct, not a class. How would I access a particular part of it?

  4. #4
    Registered User
    Join Date
    Apr 2003
    I know what most of it means but what does "new" mean?
    If you don't know what pointers are, then you won't be able to understand 'new'. There are two ways to create variables in C++, by declaring them like this(statically):

    int num = 10;

    or by "dynamically allocating memory" for them, like this:

    int* p = new int;

    'new' returns the address of the location in memory where enough memory was set aside to store an int.

    Since member variables of a class are usually private, if the user of the class is allowed to access the member variable, it will usually be through a get() function. In that case, you would have to do something like this:


    If the class provide direct access to the member variable, you can do this:


  5. #5
    Tropical Coder Darryl's Avatar
    Join Date
    Mar 2005
    Cayman Islands
    A struct and a class is basically the same thing, the only difference being that a struct members are public by default and a class's are private.

    As state above, "new" returns a pointer but to correct the example code you would need to use -> to dereference it and not . (Assuming that num is an array of person*)

    cout << num[0]->height;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C code line, pointer declaration
    By Dedalus in forum C Programming
    Replies: 2
    Last Post: 06-10-2009, 04:34 AM
  2. help again with scrolling without wrapping
    By Dukefrukem in forum C Programming
    Replies: 8
    Last Post: 09-21-2007, 12:48 PM
  3. Can't figure out a line of code...
    By bamera in forum C++ Programming
    Replies: 1
    Last Post: 10-15-2005, 07:11 PM
  4. SSCANF help
    By mattz in forum C Programming
    Replies: 7
    Last Post: 12-10-2001, 04:53 PM