When I searched online for solutions
That's your problem right there. Don't go searching the Internet and copying/pasting code you don't understand. That's for after you graduate.
I found the code
Stack<string> stringStack = new Stack<string>();
stringStack.push(17);
int a = stringStack.pop();
That won't compile. new
is for doing dynamic allocations, and returns a pointer. What you have on the left hand side (Stack<string> stringStack
) is not a pointer.
The "mysterious" *
you see annotating the left hand side (in the correct code) denotes a pointer. When it's not part of a type, it is a dereference operator, which means "look up what this pointer points to".
Dynamic memory allocation must be done in pairs... a new
and a delete
, otherwise you will leak. Demonstrated briefly:
{ // a scope begins
int x = 10; // not a pointer; stack allocated
} // a scope ends, integer automatically is gone
{ // a scope begins
int *px = new int; // px points to integer-sized memory box
*px = 10; // put 10 into that box
} // a scope ends, you didn't delete px, you leaked memory
The question of whether you should dynamically allocate something or not is discussed here, and maybe you'll find something of value in it:
Why should I use a pointer rather than the object itself?
But to confuse you further, if your professor was truly teaching "modern C++", then you'd be warned against the casual use of raw pointers:
What is a smart pointer and when should I use one?
I'll reiterate that the best thing you can do for yourself is to not try to shortcut by searching for solutions on the Internet. Follow your coursework from the beginning, and if you feel that your course or professor are lacking then supplement your education by working through a good book on your own.