Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   weird problem in c++ (http://www.go4expert.com/forums/weird-cpp-t20169/)

dark_night 23Nov2009 10:29

weird problem in c++
 
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 24Nov2009 00:32

Re: weird problem in c++
 
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 24Nov2009 07:39

Re: weird problem in c++
 
thanx Gene Poole for your reply........it works..........thanx.......


All times are GMT +5.5. The time now is 19:06.