Static class objects

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • scoobydoo666
    New Member
    • Dec 2007
    • 10

    Static class objects

    Hi
    What is the use of declaring a class object as static?
    Eg: Class Base{
    public:
    ...........
    Base(1){}
    ..........
    .........
    };
    main(){
    static Base obj(1)j;
    }
    I get compile error when I try to call default constuctor : Base()

    Thanks
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Maybe your constructor should take an int as an argument rather than a 1.

    Comment

    • scoobydoo666
      New Member
      • Dec 2007
      • 10

      #3
      Yes weaknessforcats . you are right. It was a mistake

      Class Base{
      public:
      .
      Base(){}
      ...........
      Base(int j){}
      ..........
      .........
      };
      main(){
      static Base obj(1)j;
      }

      please tell me the the use of declaring a class object as static?

      Thanks

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        You want the obect to be usable only in the file where it is created.

        Actually, this use of static in deprecated in C++ as are most uses of the static keyword, like static functions. You are supposed to use namespaces instead.

        A static object as you describe should be in an anonymous namespace.

        [code=cpp]
        namespace
        {
        Base obj(1)j;

        }
        int main()
        {

        }
        [/code]
        is the replacement for:
        [code=cpp]
        static Base obj(1)j;

        }
        int main()
        {

        }
        [/code]

        Comment

        • scoobydoo666
          New Member
          • Dec 2007
          • 10

          #5
          Thanks a lot weaknessforcats . I got it

          Comment

          • scoobydoo666
            New Member
            • Dec 2007
            • 10

            #6
            But why can't I call default constuctor?
            static Base b();

            I get compile error (KDE) :
            " error: cannot declare static function inside another function"

            Thanks

            Comment

            Working...