Question

I recently started learning C++ and I am currently reading a lot of material on it. One thing that keeps being repeated is that using extern to have some global variables is a bad practice and I should avoid it. The problem is that I cannot see an alternative to global variables in some situations, e.g. when I have 'product catalog' in one file (with names, descriptions, prices etc.) and need to display the value of an individual variable from the catalog in any other file.

One way I noticed some people avoid using extern is by using const to have constant variables.

My question is, isn't this just swapping extern for another keyword that (in this context, at least) works pretty much the same and how is that suddenly not a bad practice?

Was it helpful?

Solution

You probably want to encapsulate the data like your product catalog in some sort of object. You would then query the object to get some data out of it. If you need the object in another source file, generally you'd write a function or method that accepts the catalog object as a parameter and the caller would need to pass the object in to that method or function. So you might have this in one source file:

class ProductCatalog
{
    public:
        ProductCatalog();
        virtual void ~ProductCatalog();

        int getNumItems();
        Product* getItemAtIndex(const int index);
        // ... whatever else your product catalog needs
 };

And then in some other source file, you'd create a product catalog and then pass it to whatever functions or methods need it, like this:

void DoSomeWork ()
{
    ProductCatalog catalog;
    AddProductsToCatalog (catalog); // <- Here you pass the catalog to someone else to work with

    int numProds = catalog.getNumItems();
    for (int i = 0; i < numProds; i++)
    {
        Product* nextItem = catalog.getItemAtIndex(i);
        // ... do something with product here ...
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top