bryan sammon
bryan sammon

Reputation: 7441

c++ initialization of static object in class declaration

I have a C++ class (class1) with a static object of another class (class2) as a private member.

I know upon using the program I will have to initialize the static object, I can use a default constructor for this (undesired value).

Is it possible to initialize the static object to my desired value only once, and only if I create an object of the containing class (class1)?

Any help would be appreciated.

Upvotes: 13

Views: 34370

Answers (1)

Seth Carnegie
Seth Carnegie

Reputation: 75150

Yes.

// interface

class A {

    static B b;
};

// implementation

B A::b(arguments, to, constructor); // or B A::b = something;

However, it will be initialised even if you don't create an instance of the A class. You can't do it any other way unless you use a pointer and initialise it once in the constructor, but that's probably a bad design.

IF you really want to though, here's how:

// interface

class A {
    A() { 
        if (!Bptr)
            Bptr = new B(arguments, to, constructor);

        // ... normal code
    }

    B* Bptr;
};

// implementation

B* A::Bptr = nullptr;

However, like I said, that's most likely a bad design, and it has multithreading issues.

Upvotes: 23

Related Questions