0

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!

2
  • 1
    You are shadowing the member variable here: int *pole = new int [10]; change that part to pole = new int [10]; Commented Sep 10, 2015 at 12:22
  • And turn on your compiler warnings! gcc -Wall -Wextra... Commented Sep 10, 2015 at 14:21

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It won't compile, remove the * in front of pole = new int [10];
Ha ha. We'll publish jointly!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.