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.
Initialization of static variables in C. When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program. Static functions can be called directly by using class name. Static variables are initialized only once. Compiler persist the variable till the end of the program.
How to create a static class in C++? There is no such thing as a static class in C++. The closest approximation is a class that only contains static data members and static methods. Static data members in a class are shared by all the class objects as there is only one copy of them in the memory, regardless of the number of objects of the class.
Dynamic initialization happens at runtime for variables that can’t be evaluated at compile time 2. Here, static variables are initialized every time the executable is run and not just once during compilation. Constant initialization (i.e. compile time) is ideal, that’s why your compiler will try to perform it whenever it can.
Static variables in a class: As the variables declared as static are initialized only once as they are allocated space in separate static storage so, the static variables in a class are shared by the objects. There can not be multiple copies of same static variables for different objects.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With