"new" Keyword In C++ and "void" as a parameter... | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

"new" Keyword In C++ and "void" as a parameter...

Hey, I originally come from Java and i saw that in C++ using the "new" keyword in order to create instances of a class in not too popular - but it does exist! When do you use the "'new" keyword? What does it return (i assume the memory location of the object)? I'd also like a simple explanation of dynamic and static memory allocation... (when stuff goes on the Heap and when on the Stack). Second question: I saw people who write "void" in the main function's parameter place: int main(void) { ... return 0; } what does it change in this case?

14th Aug 2021, 8:11 AM
Yahel
Yahel - avatar
4 Answers
0
new in C++ isn't as same as new in Java. In C++ you can create variables on either Stack or Heap. new makes it on heap and return the address of the new variable. new in Java is to create an instance, new in C++ is to create a variable on heap. Also, there isn't garbage collector or such in C++. When an object exists on heap, you have to delete it manually. Basically, don't use new whenever you can so you don't need to care much about object lifecycles. On the stack it is destroyed when it's out of scope. And about the second question, I personally never do that. It exists to be compatible with C I guess.
14th Aug 2021, 9:19 AM
你知道規則,我也是
你知道規則,我也是 - avatar
0
CarrieForle, thanks! Can you clarify when do objects get destroyed on the stack? When the program is done/terminated?
14th Aug 2021, 9:55 AM
Yahel
Yahel - avatar
0
Yahel When the end of the scope is reached; as same as Java. But there are a few exceptions. Global variables, static variables (particularly in function scope), extern variables are destroyed when the program ends regardless of the scope.
14th Aug 2021, 11:31 AM
你知道規則,我也是
你知道規則,我也是 - avatar
14th Aug 2021, 11:50 AM
Yahel
Yahel - avatar