Thread: Global object

  1. #1
    Its hard... But im here swgh's Avatar
    Join Date
    Apr 2005
    Location
    England
    Posts
    1,688

    Global object

    I was wondering if the following is considered poor practice, as the object is not
    created in main.

    I placed this sort of thing in a header file and linked it and had no errors, but Dev showed that the object I had created from the class was global, as it was seperate from main.

    Code:
    #ifndef HEADER_H
    #define HEADER_H
    
    class Foo
    {
    public:
        Foo() {};
        ~Foo();
    
    private:
        int something;
    };
    
    Foo fo;  // this is considered global, is this poor practice
    
    #endif

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >I was wondering if the following is considered poor practice, as the object is not
    created in main.
    Yes, but not because the object isn't created in main. It's because the object is defined in a header file. If you include the header more than once in your project (as would be expected), you'll get multiple definition errors from the linker. The proper way to do something like this is to define the object in an implementation file and simply declare it in the header file:
    Code:
    #ifndef HEADER_H
    #define HEADER_H
    
    class Foo
    {
    public:
        Foo() {};
        ~Foo();
    
    private:
        int something;
    };
    
    extern Foo fo;
    
    #endif
    Code:
    #include "header.h"
    
    Foo fo; // Define here, link this file, and be happy
    My best code is written with the delete key.

  3. #3
    Its hard... But im here swgh's Avatar
    Join Date
    Apr 2005
    Location
    England
    Posts
    1,688
    Thanks prelude, I understand

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. synchronization object choosing
    By George2 in forum C# Programming
    Replies: 0
    Last Post: 03-22-2008, 04:33 AM
  2. Replies: 4
    Last Post: 01-23-2008, 06:21 AM
  3. ERRPR: Object reference not set to an instance of an object
    By blackhack in forum C++ Programming
    Replies: 1
    Last Post: 07-13-2005, 05:27 PM
  4. Set Classes
    By Nicknameguy in forum C++ Programming
    Replies: 13
    Last Post: 10-31-2002, 02:56 PM
  5. Set Classes
    By Nicknameguy in forum C++ Programming
    Replies: 3
    Last Post: 10-21-2002, 07:40 PM