Hello! Id like to ask a scope question if you have time. I have a function (function A) that creates an array of objects of type MyClass. Everything works great but I cannot access this array with my other functions. In order to make this array available I need to give it global scope (define it outside of any other function). However, I cannot do that either because once I declare an array outside the functions, I cannot later allocate it dynamically inside a function. So, I have a scope problem. I also tried to declare a pointer outside of functions like this:

extern MyClass *myArray;

and then within my function A I declare my array like this

MyClass *myArray[100];

This, surprsisingly, makes it possible for the other functions of the program to recognize myArray as a legitimate thing but creating a pointer like this (when done by a function other than function A) will never work:

MyClass *pointer=myArray[5];

This should work because when I do this in the function A, everything works.

What do you think Im doing wrong? Thank you for finding the time to help me!! - eric  

Dear Eric:

I think I understand your question.

You are having a problem dynamically allocating instances of a class that you have defined globally.

The only thing I can think of for you to try is to allocate the array of structures you want in a special public method of the same class that you have declared globally and do not allow the allocation of those structures dynamically outside of that class.  

You can allocate the global class statically once and for all then call public methods of that class to dynamically allocate the other structures.  

Once the structures are created you can either pass a pointer to them to the calling routine or you can manipulate them using other public methods and pass back the results.


All Answers

Answers by Expert:

Ask Experts


Titus B. Ledbetter, Jr.


C , MFC, Object Oriented, Artificial Intelligence


I have over ten years experience in the field of Computer Science, five years experience developing C/C++. I recently wrote a chess program using Object Oriented, C++, MFC.

Master's Degree Computer Science from Johns Hopkins

©2017 About.com. All rights reserved.