13

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.

4
  • You can't use a class constructor to initialize a static member. Constructors are called every time a new instance of the object is created, but statics are only initialized once. Commented May 8, 2012 at 13:42
  • 1
    @JohnDibling yes you can if you add a check. Commented May 8, 2012 at 13:43
  • 1
    @SethCarnegie: In your code below, Bptr = new B(arguments, to, constructor); isn't an initialization. The initialization is B* A::Bptr = nullptr;. Commented May 8, 2012 at 13:46
  • @JohnDibling ah, you are right, terminology mistake. Commented May 8, 2012 at 13:47

1 Answer 1

23

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.

Sign up to request clarification or add additional context in comments.

12 Comments

ok I see what you mean. Yea, the pointer thing wont work cause I can gonna be making many objects of class A
@bryansammon it doesn't matter how many you make, I will write an example.
Thanks alot, you think thats a bad design habit?
@bryansammon well, it of course depends on your situation, but I think there are more situations in which it's bad design than there are in which it's good design. I can't think of a situation in which you'd want a new seperate single object to appear after you create one of those objects. You get to make the final decision though.
@bryansammon actually nevermind, that way wouldn't work, my bad.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.