Arslan7041 wrote: |
---|
The way to solve the array issue is to allocate memory using the new operator. |
Should avoid using new and delete, as
dhayden says use STL containers instead. Otherwise investigate smart pointers.
sadij97 wrote: |
---|
Why do we use pointers? Is it because we want to save computer stress for not making copies of things rather just change it in it's original location. |
Well that is the intention, and pointers are still used under the hood in libraries like the STL and others.
But for a user of C++, one can do a lot with out using pointers.
Already mentioned doing as much as one can with the STL, it takes care of memory and has a lot of handy features.
C++ also has references, which are like an alias for another variable, and behave in a similar way to pointers. A reference must be associated with a variable (but they can go out of scope) , whereas a pointer can be made to point at anything including nothing. So a reference is safer, and one should prefer to use this wherever possible.
As, I am learning this, i always find it easy to just assign a variable. |
So use a reference if it is not a built-in type - int double etc.. That is, if it is a class - yours or an STL one like std::string, or std::vector say. Basically anything that could be big, pass by reference.
The other thing to realise here is that C++ is a federation of languages, including C, OOP C++ (classes), Template C++, and the STL.
Now what happens at school is that students write code that is barely C++ (uses iostream) but in reality is C code using raw pointers everywhere. Maybe they do this because they learnt C before C++. Also schools get their students to write their own versions of sort functions, linked lists, trees etc, so they get an understanding of how these things work. So this adds up to students not using the STL, or maybe being allowed to in a limited form depending on what the task is.
So we are at cross purposes here: on one hand it's good to get exposure to C coding; on the other, modern C++ is quite different.
Also, apparently there are a lot of teachers behind the times, they still teach
new
and
delete
for example. Maybe they see it as a more modern form of
malloc
and
free
. Maybe there is a lot of work in changing the syllabus to teach smart pointers instead.
On top of all that, there are lots of "old" examples of code on the internet.