I have two ‘simple’ questions in C++.
1- I want to make a variable shared by some methods in a class, so what i am doing is declaring the variable in the header file and make it global to the class. Hence, all methods will have access to it. Is this the right way of doing it ?
2- Following my first point, if i declare variable N as double *N in the header. Then inside one of my methods, i do
N = (double*) malloc (sizeof(double)*50);
I know that N will have a memory allocation inside the function. My question is: is this memory reserved only inside the function or it stays for the global N all the time ?
If the memory won’t be reserved for N, then this method wouldn’t be a good method, as the system might overwrite the values of N later during the program.
Please kindly advice, Thank you
EDIT: Thank you all for the input and for editing my question. Apparently i mistakenly called my variable as global while it is actually a class member. I thought this declaration is called global since the variable is global for the methods inside the class. Hope i ask a ‘smarter’ question next time 🙂
Let’s clear things up a bit. Assuming this is in header
members.h:Note that variables/data members like
aorcdo not require explicit allocation. On the other handddoes, because it is a pointer. Note also that in C++ you usenew()rather thanmalloc().This is source file
members.cpp:I hope I’ve been clear enough and covered your doubts.