Guru Prasad
Guru Prasad

Reputation: 4233

Store object of a class within the class itself

How do I store an object of a class within the class itself?

I know that I have to use the static keyword to accomplish what I want. Thus the class should look something like:

class my_class {
public:
    static my_class instance;
    my_class() {
        my_class::instance = this
    }
};

Below is the exact code as it appears in the class

namespace ArmISA {
    class ISA {
        protected:
            static ISA* isa;
            MiscReg miscRegs[NumMiscRegs];
            const IntRegIndex *intRegMap;
            .....
        public:
            ISA() {
                ISA::isa = this;
                ...
            }
        ...
    };
}

The error I get is:

error: could not convert 'ArmISA::ISA::isa' from 'ArmISA::ISA*' to 'ArmISA::ISA'

Upvotes: 0

Views: 1389

Answers (3)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145457

To initialize a static member variable of non-integral type (or, in C++11, non-constexpr), do that outside the class.

For example:

struct Foo
{
    static Foo bar;
    double x_;
    Foo( double x ): x_( x ) {}
};

// Preferably in an implementation file:
Foo Foo::bar( 3.14 );

The declaration outside the class is always formally the definition, which provides storage for the variable (needed if you ever take the address).


If you want to provide a header-file only module, one alternative is to provide access to the static variable via a function, like this:

struct Foo
{
    static Foo& bar()
    {
        static Foo theBar( 3.14 );
        return theBar;
    }

    double x_;
    Foo( double x ): x_( x ) {}
};

Another technique is to inherit from a class template that provides the static variable.

Upvotes: 0

Zdeslav Vojkovic
Zdeslav Vojkovic

Reputation: 14591

my_class::instance = *this; will work, but I hope that you are aware that every time you create a new instance of the class, your instance member will be overwritten. Additionally, this means that instance is a copy of *this and not a reference - changes to one are invisible to the other.

Another option is to declare instance as a pointer, in which case both pointers refer to the same object and then instance = this; would compile:

static my_class* instance;

However, I am not sure what exactly you try to achieve.

Upvotes: 1

Oswald
Oswald

Reputation: 31685

this is a pointer. Use my_class::instance = *this.

Upvotes: 0

Related Questions