weird problem in c++

Discussion in 'C++' started by dark_night, Nov 23, 2009.

  1. dark_night

    dark_night New Member

    Joined:
    Nov 18, 2008
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    hi all,
    i came to a strange problem...i have 3 class...
    Code:
    //resource.h
     #include "myclass.h"
     #include "a.h"
     #include "b.h"
     
    Code:
     //myclass.h
     class myclass
     {
         public:
         int num;
     };
     static myclass mylist;
     
    Code:
    //a.h
    #include<stdio.h>
    class A
    {
        public:
        void print();
    };
    
    Code:
    //a.cpp
    #include "resource.h"
        void A::print()
        {
            mylist.num=10;
            printf("%d",mylist.num);
            B b;
            b.print();
        }
    
    
    Code:
    //b.h
    #include<stdio.h>
    class B
    {
        public:
        void print();
    
    };
    
    
    Code:
    //b.cpp
    #include "resource.h"
        void B::print()
        {
            printf(" %d",mylist.num);
        }
    
    
    Code:
    //main.cpp
    #include "resource.h"
    int main()
    {
        A a;
        a.print();
        getchar();
        return 0;
    }
    
    i want the output 10 10
    but the output is 10 0
    why???i cant understand...please help...
    thanx....
     
  2. Gene Poole

    Gene Poole New Member

    Joined:
    Nov 10, 2009
    Messages:
    93
    Likes Received:
    5
    Trophy Points:
    0
    static myclass mylist; is declared in a header file, therefore, each file that includes resourse.h has a different copy of mylist. Declare it (not static) in one and only one of your cpp files and put an extern myclass mylist; in each module that must access it (or in a header common to all modules).
     
  3. dark_night

    dark_night New Member

    Joined:
    Nov 18, 2008
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    thanx Gene Poole for your reply........it works..........thanx.......
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice