Hello,
Quick intro: I'm a professional front-end web developer & graphic designer, with some experience with Java. I am trying to learn C++ just for a hobby.
I'm going through a text book (Sam's teach yourself C++), and have been writing little programs to help cement the lessons along the way.
I thought I understood what the book was saying about pointers and dynamic numbers of objects: that the programmer has to set aside memory space on the heap in order to create a dynamic amount of objects at runtime; and the way to do this is to use the "new" keyword to create a pointer to that memory space.
However, I tried writing a program that defied that logic, and it worked just fine, leaving my quite confused.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include <iostream>
using namespace std;
main()
{
cout << "Enter no. of dynamic variables to create: ";
int count = 0;
cin >> count;
// *** I was expecting one of the below two lines to cause a compiler error ***
// create dynamic array
int numbers[count]; // "new" keyword -not- used
// fill numbers array with dynamic amount of ints
for (int x = 0; x < count; x++)
numbers[x] = x; // "new" keyword -not- used
// Print variables' memory locations
for (int x = 0; x < count; x++)
cout << endl << &numbers[x];
cout << endl << endl; // just for neatness
}
|
Second question, why do I need to create a pointer with the new keyword, why not just create an object like in Java? I guess I can do the same thing as below, I just don't understand why it has to be like that, and I'm afraid it's because I don't really understand the whole deal with pointers. Maybe my head is still in Java-world.
If someone can explain, I'd appreciate it.
1 2 3 4 5 6 7 8 9 10 11
|
MyObject * p_obj = new MyObject();
MyObject obj = *p_obj;
// OR -->
MyObject obj = *(new MyObject());
// Why the need to use a pointer? Why not just MyObject o = new MyObject(); ?
|