Reputation: 5
I have a problem. I want to operate with single element of an array, which is generated in member function, but it doesn´t work. Here is my code:
using namespace std;
class Example
{
public:
int *pole;
void generate_pole();
};
void Example::generate_pole()
{
int *pole = new int [10];
for (int i = 0; i < 10; i++)
{
pole[i] = i;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
Example reference;
reference.generate_pole();
cout << reference.pole[1] << endl; //there is the problem
system("pause");
return 0;
}
How can I get an access to the element? And where is the real problem? Thank you!
Upvotes: 0
Views: 71
Reputation: 234875
int *pole = new int [10];
is creating an identically named variable pole
in local scope. This is shadowing the member variable.
A fix, drop the int*
from the errant line: pole = new int [10];
That said, I'd be inclined to use a constructor to set the member variable in this case: certainly you should initialise pole
to nullptr
by default. This is so you can delete[] pole
in a destructor when an instance of your class goes out of scope. Else your code will leak memory like a colander leaks water.
An other way would be to use std::vector<int> pole;
and let the C++ standard library take care of all the memory for you.
Upvotes: 2
Reputation: 2084
The problem is, that you shadow pole's name in the scope of the function by redeclaring it. leave the int *
in front of pole behind, in generate_pole
, and it should work.
An example for shadowing:
int i = 0; // i is 0
std::cout << "before scope: " << i << std::endl; // prints 0
{
int i = 1;
std::cout << "inside scope: " << i << std::endl; // prints 1
}
std::cout << "behind scope: " << i << std::endl; // prints 0
Upvotes: 1