Thread: Access global variable from a class

  1. #1
    Registered User
    Join Date
    Dec 2013
    Posts
    23

    Arrow Access global variable from a class

    Hello everyone,

    i cannot access global variable that i declared in the main.cpp file from inside a class.

    Code:
    #include<iostream>
    #include<vector>....
    #include <myClass.h>
    
    using namespace std;
    
    //gloval var here....
    
    int age=99;
    
    
    int main() {
    
    //create an instance of myclass here.
    
    }
    From within myclass a method needs to access the age value

    How can i do this?

    tried with extern int age=99; too

  2. #2
    Registered User
    Join Date
    Mar 2015
    Posts
    184
    I never use globals, but did you try using an empty scope resolution operator ::varname ?

  3. #3
    Registered User
    Join Date
    Dec 2013
    Posts
    23
    Quote Originally Posted by jiggunjer View Post
    I never use globals, but did you try using an empty scope resolution operator ::varname ?
    Not yet, going to try
    Thank you

  4. #4
    Registered User
    Join Date
    Mar 2015
    Posts
    184
    I juat noticed you included your class first. You might need to forward declare the variable, in the myclass.h file, above your class.

  5. #5
    Registered User
    Join Date
    Dec 2013
    Posts
    23
    @jiggunjer
    How can i do this?

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Like this:
    Code:
    extern int age;
    But, you should not be using global variables as they make it more difficult to reason about (and debug, maintain, etc) your program. Furthermore, the larger the scope of an identifier, the more descriptive it should be. Within some local scope, or as a class member, "age" might be a descriptive name. For a global variable (or constant), "age" is a horrible name: age of what? Some people might also use a bit of name decoration (e.g., prefix with a "g_") to make it obvious that a variable is global.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User
    Join Date
    Dec 2013
    Posts
    23
    It's just as example.
    I tried to declare extern int age, but still not visible outside the main.cpp file. As for the coding style, i have to improve a lot.

    Trying to explain what i want to do:

    i have to say that the type of vector isn't int, btw, but a number of instantiated class Animal that i push in the vector.

    i do the following:

    extern std::vector<Animals> my_anymals;

    Animal dog ("Pluto", 10, 40);
    Animal cat ("Silvester", 5,10);

    then i do:

    my_animals.push_back(dog);
    my_animals.push_back(cat);

    now, how my Animal class should look like to access the vector my_animals that reside in the main.cpp declared in his global space?

    Could you please provide an example?

    Thank you in advance

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by AmiPlus
    now, how my Animal class should look like to access the vector my_animals that reside in the main.cpp declared in his global space?
    Your Animal class definition should be in a header file like this:
    Code:
    #isndef ANIMAL_H_
    #define ANIMAL_H_
    
    #include <vector>
    
    // animal.h
    
    class Animal
    {
    public:
        void foo();
    
        // ...
    };
    
    extern std::vector<Animal> my_animals;
    
    #endif
    If they are not defined within the class definition, your Animal class members should be defined in a source file like this:
    Code:
    #include "animal.h"
    
    std::vector<Animal> my_animals;
    
    void Animal::foo()
    {
        // ...
    }
    Now, you can write within your main function:
    Code:
    #include <iostream>
    #include "animal.h"
    
    int main()
    {
        // ...
    
        std::cout << my_animals.size() << std::endl;
    
        // ...
    }
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    To clarify, by default, global variables are visible across all source files. You can disable this behavior by making said variable static (Only works with globals! Static for non-globals have a different meaning!). Example:

    std::vector<XAnimal> MyAnimals; // Accessible to all source files
    static std::vector<XAnimal> MyAnimals2; // ONLY accessible the source file it was defined

    Now, the compiler is not psychic. Every source file is treated as a separate contained "unit" of compilation. The compiler doesn't care--or know--about anything in other source files. That includes global variables. You just as you can't call functions in other source files without first declaring them in the source file you're using them (that's why we use headers), we have to forward declare the global variable so the compiler knows it's there. Example:

    extern std::vector<XAnimal> MyAnimals; // OK; Now we can access this global variable defined in another source file in this source file.

    But what happens if we "lie"? What happens if we say there IS a variable that's not actually there? What will happen is that the compiler will happily accept the code, but at the linking stage, which puts all source files together into an executable, you will get an error because the "linker" will need to find this global variable, but it can't because it doesn't exist!

    So that's a small primer. Remember that globals variables are evil, though. Use them sparingly.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #10
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    Quote Originally Posted by Elysia View Post
    To clarify, by default, global variables are visible across all source files. You can disable this behavior by making said variable static (Only works with globals! Static for non-globals have a different meaning!). Example:

    std::vector<XAnimal> MyAnimals; // Accessible to all source files
    static std::vector<XAnimal> MyAnimals2; // ONLY accessible the source file it was defined.
    It should be noted that C++ also provides for an unnamed or anonymous namespace, that has the effect of confining access to the current translation unit, much like static above. Using static is a holdover from C, and my preference is always to use the anonymous namespace in C++ code.

    In addition to the above, we can add:

    Code:
    namespace
    {
        std::vector<XAnimal> MyAnimals3; // Also only accessible within the source file in which it is defined
    }
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Oh yes, completely forgot about anonymous namespaces... nice reminder.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Registered User
    Join Date
    Dec 2013
    Posts
    23
    Thank you for the explanations.

    ive already tried :extern std::vector<XAnimal> MyAnimals;

    i get this errors:

    error: storage class specified for 'MyAnimals'

    and

    error: redefinition of 'class XAnimal'
    error: previous definition of 'void XAnimal:: etc etc...

  13. #13
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    error: storage class specified for 'MyAnimals'
    O_o

    You can't put the declaration inside a class definition.

    error: redefinition of 'class XAnimal'
    You can define normal methods of a class within the definition for a class unless you also mark the method with the `inline` keyword.

    Soma
    “Salem Was Wrong!” -- Pedant Necromancer
    “Four isn't random!” -- Gibbering Mouther

  14. #14
    Registered User
    Join Date
    Dec 2013
    Posts
    23
    @laserLight

    Thank you for the informations.

    Btw, i need to access the vector created in the main from within a class:

    This is the Main.cpp

    Code:
    #include <iostream>
    #include <sstream>
    #include <cstdlib>
    #include <string>
    #include <vector>
    #include "include/object.h"
    #include "include/animal.h"
    
    
    using namespace std;
    
    vector<CObject> Obj;
    
    
    CObject Key ("Collar", );
    CObject Chain ("Chain", );
    Cobject Bell ("Bell")
    
    int Stable=0;
    
    Animal sheep ("Snow", "Sheep", 1);
    string myName=sheep.getName();
    Animal dog ("Lassie", "dog", 1);
    string dogName=dog.getName();
    
    vector<Animal> animalList;
    
    int main()
    {
        bool running=true;
        //Obj and other vector must be initialized, first, then push the object
        Obj.push_back(Key);
        Obj.push_back(Gold);
    
        animalList.push_back(sheep);
        animalList.push_back(dog);
    
        system("CLS");
        cout << "The " sheep.type << " name is: " << sheep.getName << endl;
        cout << "The " dog.type << " name is: " << dog.getName << endl;
        return 0;
    }
    the animal.h class:

    Code:
    #include <iostream>
    #include <vector>
    #include <string>
    
    using namespace std;
    
    extern vector<int> Obj; // doesn't work conflicting declaration 'std::vector<CObject> Obj'
    /*here a would like to access the object created in main (vector<CObject> Obj;), iterate through it and modifying the values, adding or removing elements.
    Many suggested to avoid using globals */
    
    struct Object {
            string name;
            string type;
            int status;
    };
    
    class Animal{
    
      public:
        string _name;
        string _type;
        int _inStable, _status=0;
    
        vector<int> objects;
        Animal (string, string, int);
    
        string getName () {return (_name);}
        void addObject(string objName);
        void removeObject(string name);
    
    };
    
    void Animal::addObject(string ObjName) {
    
    //to do
    
    }
    
    void Animal::removeObject(string name){
    
    //to do
    }
    
    Animal::Animal(string name, string type, int status) {
    
      _name = name;
      _type = type;
      _status = status;
    
    }
    The object class:

    Code:
    #include <iostream>
    #include <vector>
    #include <string>
    
    
    using namespace std;
    
    class CObject{
    
      public:
        string _name;
        string _type;
        int _status;
    
        CObject (string, string, int);
        string getName () {return (_name);}
        void setName(string nm) { _name=nm;}
    
        int getStatus() { return _status;}
        void setStatus (int sts){
            _status=sts;
        }
    
    };
    
    
    CObject::CObject (string name, string type, int status) {
    
        _name=name;
        _type=type;
        _status=status;
    
    }

  15. #15
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    Code:
    CObject Chain ("Chain", );
    Code:
    Obj.push_back(Gold);
    Code:
    cout << "The " sheep.type << " name is: " << sheep.getName << endl;
    O_o

    This is the Main.cpp
    o_O

    If true, you need to fix all the errors your compiler is telling you to fix.

    Many suggested to avoid using globals
    Yet, you are still using globals.

    Soma
    “Salem Was Wrong!” -- Pedant Necromancer
    “Four isn't random!” -- Gibbering Mouther

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. access variable from other scope without global declaration?
    By unixmania in forum C++ Programming
    Replies: 1
    Last Post: 08-08-2013, 03:03 AM
  2. Global/Static function/variable slower to access?
    By JohnLeeroy in forum C++ Programming
    Replies: 1
    Last Post: 07-20-2011, 11:56 PM
  3. Global Access to Global Class without so many pointers
    By parad0x13 in forum C++ Programming
    Replies: 1
    Last Post: 11-11-2009, 02:48 PM
  4. global variable access, from c to c++
    By manav in forum C++ Programming
    Replies: 17
    Last Post: 04-28-2008, 03:48 AM
  5. static class variable vs. global variable
    By nadamson6 in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2005, 03:31 PM