The major problem I find at the moment is with "initializing pointers" .
In Pascal, all you had to do is declare NEW(POINTER). In C++, I am lost as - correct me if i am wrong - you have to declare a "dummy" variable in order to initiate a pointer.
Let me put in this way: I want to build a class that will be chained by pointers. In Pascal, all I had to do is add the class a pointer, I called it next, of the same kind that it is nested in.
How do I it in C++?
Pointers work exactly the same way in C++ as they do in Pascal. The only difference is in how you allocate and free the things being pointed at.
For instance, you can declare a local variable and point to it, eg:
This would be equivalent to this in Pascal:
Or, you can use
newanddeleteto work with variables allocated dynamically, eg:Which is equivalent to this in Pascal:
However, modern C++ code should strive to avoid using
new/deletedirectly as much as possible. Use smart pointers instead (std::unique_ptrandstd::shared_ptr, viastd::make_unique()andstd::make_shared()), which free memory automatically when they go out of scope and get destroyed. This helps make code safer and more self-documenting as to the ownership semantics of pointed-at data. Use raw pointers only where needed to access data without transferring ownership of it, eg:The type of class you describe is more formally known as a node/element of a "linked list", which is commonly implemented using
new/delete, eg:A linked-list is not a good example for using smart pointers, though. Yes, the
headpointer could be a smart pointer, at least. But you would still have to iterate the list destroying the individual nodes, before theunique_ptrdestroys theheadnode. And you might be tempted to make thenextpointers be smart pointers too, but doing that would be a bad idea, as recursive destructor calls can blow up the call stack when destroying large linked-lists. Iterative loops are more suitable for destroying linked-lists, and havingnextbe a smart pointer is not a good fit for that use-case.But, in any case, C++ has built-in standard classes for double-linked lists (
std::list) and single-linked lists (std::forward_list), which handle the linking pointers for you, so you can focus more on your class data and less on how the class instances are linked together, eg: