C ++ initialization of a static object in a class declaration

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

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

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

Any help would be appreciated.

+3
source share
1 answer

Yes.

// interface

class A {

    static B b;
};

// implementation

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

, A. , , , , .

, :

// interface

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

        // ... normal code
    }

    B* Bptr;
};

// implementation

B* A::Bptr = nullptr;

, , , , , .

+9

All Articles