Could someone tell me what this like of code means:
I know what most of it means but what does "new" mean? How do I access the height of a certain person?Code:num[1] = new Person("James", 6, 75); num[2] = new Person...
Cheers.
Could someone tell me what this like of code means:
I know what most of it means but what does "new" mean? How do I access the height of a certain person?Code:num[1] = new Person("James", 6, 75); num[2] = new Person...
Cheers.
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
You'd need to take a look at the class defination though.Code:cout << num[0].height;
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?
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):I know what most of it means but what does "new" mean?
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:
cout<<num[0]->getHeight();
If the class provide direct access to the member variable, you can do this:
cout<<num[0]->height;
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*)
Code:cout << num[0]->height;