Hi there,
I'm having a little trouble getting this, so please excuse me if my question and description sounds confusing or juvenile.
I'm creating a new class called 'Rec'.
And essentially I want to reuse the same instance object (myInstance) every time. So it would be created the first time i initiate the constructor, but the following times it would just refer back to the same one.
-
//the specification
-
class Rec {
-
public:
-
~Rec();
-
static Rec* instance();
-
-
protected:
-
Rec();
-
-
private:
-
static Rec* myInstance;
-
};
-
But my question is, how do I actually go ahead to declare a new Rec instance in my Main method? As in, what does that actual line of code look like? I can't figure out how to use this constructor: static Rec* instance();
Thanks a lot for your help
What you want is the singleton class, but you have it just a little bit backwards. You need to be able to declare an instance, but only one instance of the class.
This means the constructor needs to be private, you need a reference of the class to live locally, so that you can keep, modify, and return that instance as your singleton, you need to be able to get that instance, and then the tricky, but not too tricky part, is to create one and only one reference. Like I said, you're very close, but there are a few things you have backwards.
-
//the specification
-
class Rec {
-
public:
-
~Rec();
-
static Rec* instance();
-
// I'd have this as getInstance() - just for "good programming practice", but that's good
-
-
private:
-
static Rec* myInstance;
-
// also good - this takes care of having one instance
-
// but you also need the constructor here, one that will only instantiate one instance of it
-
static Rec() {
-
if (myInstance == null)
-
myInstance = new Rec();
-
else
-
return myInstance;
-
};
-
};
-
I'm not sure if this is the case in C++, but with Java having an omnipotent superclass of Object, you would need to overload the copy constructor, throwing an exception when they attempted to access it. (This would also require making the whole class final as well.) I'm not sure the Rec() code is 100% right, but it should definitely be enough to get you going.