I\'m a python programmer who sees a lot of C++ code but doesn\'t know the langua
ID: 653039 • Letter: I
Question
I'm a python programmer who sees a lot of C++ code but doesn't know the language and there seems to be two ways to initalize a class. I was hoping that someone can tell me the difference.
class Point {
int x, y;
public:
int get_x();
int get_y();
Point(int, int);
}
// ok we are going to leave the methods and constructors unimplemented for brevity
// now here's the part that puzzles me
Point p(5, 5); // ..or
Point p = new Point(5, 5);
What's the diffrence between the two?
Explanation / Answer
One of those variables lives on the stack, the other on the heap. The correct syntax is this:
Point p(5, 5);
Point* p = new Point(5, 5);
The first one creates an object on the stack. When p goes out of scope, it'll be removed automatically. The second, creates a point object on the heap. Until you remove it manually, it'll remain in memory.
In the second case, p is a pointer to the Point object, while in the first case p is the point object.
Python essentially does only the second version and doesn't do the first. Python is garbage collected, so it'll also remove the point object from memory if it is no longer referenced.
However, I should mention (see comments) that the prefered method to create objects on the heap is to use smart pointers. See DeadMG's answer for more details.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.