Sharing an instance variable between all instances of a class (C++).

Started by
2 comments, last by Angex 19 years, 8 months ago
What I want to do is have a pointer in a super class that once initialised has the same address for all instances of it's subclasses. I thought that I could use the static keyword but I keep getting unresloved external symbol errors during the linking phase. Do demonstrate what I mean I wrote a simple example in java:

public class Gremlin {
    protected static int numberOfGremlins = 0;

    public Gremlin() {
        System.out.println("There is " + (++numberOfGremlins) + " gremlin(s) !\n");
    }
}



public class EvolvedGremlin extends Gremlin {
    protected static int numberOfEvolvedGremlins = 0;

    public EvolvedGremlin() {
        super();
        System.out.println("There is " + (++numberOfEvolvedGremlins) + " evolved gremlin(s) !");
        System.out.println("There is " + numberOfGremlins + " gremlin(s) altogeather !\n");
    }

    public void countGremlins() {
        System.out.println("I counted " + numberOfGremlins + " gremlin(s) !");
    }
}

EvolvedGremlin inherits the nuberOfGremlins from Gremlin, but the value is the same for every instance of EvolvedGremlin. So if I created two EvolvedGremlin objects, and two Gremlin objects, and then got an EvolvedGremlin to count the number of Gremlins the output would be:

There is 1 gremlin(s) !

There is 1 evolved gremlin(s) !
There is 1 gremlin(s) altogeather !

There is 2 gremlin(s) !

There is 3 gremlin(s) !

There is 4 gremlin(s) !

There is 2 evolved gremlin(s) !
There is 4 gremlin(s) altogeather !

I counted 4 gremlin(s) !

However I am at a loss as to how this could be done in C++ ?
Advertisement
Ok, say you declare it in a header file:
class Gremlin {  static int numberOfGremlins;  // And so on...

You'll also need to define it somewhere, the best place would be in the source file corresponding to the header:
int Gremlin::numberOfGremlins=0;
What is the exact error you are getting? Using static is correct here. Something like:

class Gremlin{public:   Gremlin();protected:    static int numberOfGremlins;};int Gremlin::numberOfGremlins = 0;Gremlin::Gremlin(){  numberOfGremlins++;}



--------------
Andrew
Thanks guys, I did not realise you needed to add a definition within the source code, so I only had the declaration in the header file; which explains the error.

This topic is closed to new replies.

Advertisement