1

I have class A such that:

class A {
    static int i;
    A();
    f1();
    f2();
    static void intitiaize();
    // snipped rest
}

void initialize() {
  A::i = 0;
}

in a header file.

I have a intiialize function for the class which initializes the static variables in main method in second file. After this i create an object of A to call a.f1().

When I try to create another object of A in file three the compiler complains saying "no reference to class A". So included the header in this third file.

I get an error about multiple definitions of A.

How should I proceed? I have include guards around the class file.

pmr
  • 58,701
  • 10
  • 113
  • 156
Anerudhan Gopal
  • 379
  • 4
  • 13

2 Answers2

2

You want a declaration of A::i in the header (and you can get rid of your initialize():

//whatever.h:
class A{
    static int i;
    A();
    f1();
    f2();
    ...
}; // don't forget the semicolon on the end.

Then you need a definition of the variable in one CPP file:

// whatever.cpp:
int A::i = 0;

Then include the header wherever you're going to use objects of the class, and just compile the .CPP file and link it with the others that use this class.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • thanks .. found another mistake n my code.. and stupid thing that I had done was to give function defn in header files .. this was again causing problem because the same defn was getting included in both the c files.. – Anerudhan Gopal Mar 30 '12 at 09:53
0

With const integral numbers you can actually initialize it in the header. This includes bool and char types. Jerry's approach will work with any type and if it isn't const.

  class A{
      static const int i = 0;
      ...
  }
kossmoboleat
  • 1,841
  • 1
  • 19
  • 36
  • You are correct, changed it accordingly. This [question](http://stackoverflow.com/questions/185844/initializing-private-static-members) gives more details on the issue. – kossmoboleat Mar 30 '12 at 16:13