-
'new' keyword
I feel bound to explain first off that my entire knowledge of the use of the 'new' keyword comes from Java
everytime I come to a place in my c++ apps where in java I would have used the word new, I try to put new and my compiler yells and screams at me
how do I use the new keyword in c++?
-
show some code of an attempt to use new or something
EDIT
or read the tutorial,
http://faq.cprogramming.com/cgi-bin/...&id=1043284351
-
new is used to Dynamicly allocate memory. Unlike java not every thing is created this way. you can just do
Code:
MyClass var1 = MyClass(constructorarg);
Now what the new keyword does is dynamicly allocate memory for an object on the heap, and then return the ADDRESS to that location. Now what you need to do if you want to do this, is use a pointer (something you didn't deal with dirrectly in Java) here is an example
Code:
MyClass *var1 = new MyClass(constructorarg);
Notice the "*" in there, that specifies that its a pointer, which simply holds the address to the location. if you wish to use the object you have allocated, you need to dereference the pointer, using the *, or their are some other operators you can use to do this as well. Read up on pointers and dynamic memory allocation and you should be able to find this information and more.
OH and don't forget to "delete" the variable when your done, becuase if you allocate more memory, and use that pointer again without using delete first, you get what is some times called a memory leak, nastly little problem that can really screw you up.
-
If you use 'new', then you have to have a pointer variable on the left side of the equals sign. Also, in C++ when you use 'new' to create an object, the object stays in scope until it is deleted, which is much different than a normal object, which goes out of scope as soon as the block it was declared in ends.
-
Try running this code:
Code:
#include<iostream>
using namespace std;
class Apple
{
public:
int num1;
int num2;
int num3;
};
int main()
{
Apple A;
Apple* p = &A;
cout<<sizeof a<<endl;
cout<<sizeof p<<endl;
return 0;
}
On my computer that outputs 12 and 4. That shows that the variable A is an object in memory that takes up 12 bytes(4 bytes per int variable). On the other hand p is a variable in memory that stores an address of A, which only requires 4 bytes. So, they are different.
I think that references to objects in Java are like pointers to objects in C++. In Java, a statement like this:
Apple A = new Apple();
creates the variable A and 'new' returns a 'reference' to a newly created object in memory. If there was a way to look at the sizeof A in Java, I think it would be something small like 4 bytes--not 12 bytes. The reason you have 'references' or 'pointers' is so that you can pass something that is 4 bytes back and forth between functions rather than something that could be 1000's of bytes in size for a large array or large object.