weird problem in c++

dark_night's Avatar, Join Date: Nov 2008
Newbie Member
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....
Gene Poole's Avatar, Join Date: Nov 2009
Contributor
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).
dark_night like this
dark_night's Avatar, Join Date: Nov 2008
Newbie Member
thanx Gene Poole for your reply........it works..........thanx.......