C++ declaring a static object in a class - c++

I'm trying to declare a static object of a class A that I wrote in a different class B, like this:
class A // just an example
{
int x;
public:
A(){ x = 4; }
int getX() { return x; }
};
class B
{
static A obj1; // <- Problem happens here
public:
static void start();
};
int main()
{
B::start();
}
void B::start()
{
int x = obj1.getX();
}
What I want to achieve is to get int x in B::start() to equal int x in class A (4).
I tried googling all this for the past hour and all I understood was that C++ doesn't allow static objects' declarations. Is that correct?
If so, here's my question. How can I get the same result? What are my available workarounds? Keeping in mind that the rest of my code depends on the functions in class B to be static.
Error
error LNK2001: unresolved external symbol "private: static class A B::obj1"
Thanks!

You should initialize static var, the code:
class A // just an example
{
int x;
public:
A(){ x = 4; }
int getX() { return x; }
};
class B
{
static A obj1; // <- Problem happens here
public:
static void start();
};
A B::obj1; // init static var
int main()
{
B::start();
}
void B::start()
{
int x = obj1.getX();
}

As thinkerou said, you need to include the declaration of the variable:
A B::obj1;
For normal, non-static member variables you don't need this step because the variables are declared behind the scenes as part of the constructor. These variables are then tied to the instance of the class you just constructed. But static variables are not tied to any instance of a class; they are shared by all instances of a class. So constructors can't properly deal with them.
C++ gets around this by making you manually declare (and optionally initialize) any static member variables. Depending on where they are declared, they typically get constructed before your main() function starts, so they are available for use immediately.

Related

How can i modify variables in static member function?

I have a code below, i want to modify class's variables in static function but there is some error.
How can i fix it with "this" pointer?
There is no access to "this" pointer for static members in class,on the other hand I am trying to make an access to class variables in Static member function, therefore i am looking for a way to use "this" pointer of class "me" to do it.
class me {
public:
void X() { x = 1;}
void Y() { y = 2;}
static void Z() {
x = 5 ; y = 10;
}
public:
int x, y;
};
int main() {
me M;
M.X();
M.Y();
M.Z();
return 0;
}
I got this error :
invalid use of member ‘me::x’ in static member function.
You have two ways to do it :
Define your members as static if they are used in a static method.
Implement Dont use of static methods when class's members are non-static
Generally, the memory of static members or methods created once even when you dont create an object of your class. So you cannot use of a non-static members in a static method, because non-static members still have no memory While static methods have memory...
Try this :
public:
static void X() { x = 1;}
static void Y() { y = 2;}
public:
static int x;
static int y;
Dont forget to initialize static members :
int me::x = 0;
int me:y = 0;
You cannot use of this pointer inside a static method, because this may only be used inside a non-static member function. Notice the following :
this->x = 12; // Illegal use static `x` inside a static method
me::x = 12; // The correct way to use of `x` inside a static method
You can pass a pointer to an instance to the method:
class me {
public:
void X() { x = 1;}
void Y() { y = 2;}
static void Z(me* this_) { // fake "this" pointer
this_->x = 5 ;
this_->y = 10;
}
public:
int x, y;
};
int main() {
me M;
M.X();
M.Y();
M.Z(&M); // this works, but
// usually you call static methods like this
// me::Z(&M);
return 0;
}
You are trying to use a non-static member from a static member function. That's why it's giving you an error.
You can fix this by making the member function non-static (by removing static keyword). You could also make the variable static, so that your static member function can access it, but if you do so, the two other functions will still not compile.
Static method can access static members only.
class me {
public:
void X() { x = 1;}
void Y() { y = 2;}
static void Z() {
x = 5 ; y = 10;
}
public:
static int x, y;
};
int main() {
me M;
M.X();
M.Y();
M.Z();
return 0;
}
Adding to that #nivpeled said, think about this:
You may create several instances of me on your program. Which ones of the instances the static Z() method should modify?
I have the ultimate solution for you here lol.
I've asked this question so many time but instead of thinking or trying to solve the problem people starts judging my design which I think is funny.
So I have to explain that in some situations you will be in need to make static members gain access to non static ones, such case when you use a scripting interface in you program(Lua for example) that interface can only access static members of a class, which those members need to access to non static, anyways lets see how to do it.
class me {
public:
me() { This = this; } // Or you can assign it wherever you want
void X() { x = 1;}
void Y() { y = 2;}
static me* This; // Here is our "this" pointer :P
static void Z() {
This->x = 5 ; This->y = 10;
}
public:
int x, y;
};
//Remember to initialize it to avoid any linker's errors
me* me::This = nullpter; // or NULL or even 0
int main() {
me M;
// now you can access "this" pointer the usually way
M.X();
M.Y();
M.Z();
return 0;
}
After a while of thinking this is the most efficient solution i found.

Overcoming static initialization order fiasco when a singleton object is involved

I have a singleton class defined in file x.h
class x
{
public:
static x* x_instance;
static x* create_x_instance
{
if(!x_instance)
x_instance = new x;
return x_instance;
}
void someMemberFunction()
private:
x() { //some code}
};
extern x *x_interface;
In x.cpp I have the following:
x *x::x_instance = 0;
x *x_interface = x::create_x_instance();
In y.cpp, in the constructor of a another singleton class, I have
x_interface->someMemberFunction();
I get a seg fault because y gets initialized before x. What is the correct way to solve this? I have read many articles on this, but I am still confused.
Just to be clear, using a static member of a static function avoids initialization order problems:
class x
{
public:
static x* get_instance()
{
static x* theInst = new x;
return theInst;
}
void someMemberFunction();
private:
x() { //some code}
};
Later code gets x like this:
x* handle = x::get_instance();
The above is minimal, it should be further improved to manage x lifetime. It might be better to just have theImpl be a static x rather than pointer-to-x, and get_instance() return a reference instead of a pointer.
allow the compiler to generate the singleton on first use by initialising it as a static member of a static function.
Additionally, you can go further and give your singleton object value semantics with zero cost while offering may benefits:
class x
{
struct impl
{
void someMemberFunction() {
}
};
static impl& get_impl() {
static impl _{};
return _;
}
public:
void someMemberFunction()
{
return get_impl().someMemberFunction();
}
};
int main()
{
auto a = x();
a.someMemberFunction();
}
Why do you need a x_interface as global or static instance as you can get the instance of class x from anywhere at any time using static method : create_x_instance ?
I think best way to use it in class y is as :
(x::create_x_instance())->someMemberFunction();

Private static class members

When we declare a member variable static, it is shared between all instances of the class. I've heard that you should think of the variable belonging to the class itself, not any instance. This lets us initialize the variable without instantiating any object of the class, which makes sense.
class Something
{
public:
static int s_nValue;
};
int Something::s_nValue = 1;
But why are we allowed to initialize a private static member?
class Something
{
private:
static int s_nValue;
};
int Something::s_nValue = 1;
Does private even mean anything when we are talking about static members?
Yes, it does mean something. Consider the following example, which throws a compiler error, because the member is private. Being able to initialize a private variable is not the same as being able to change it from any context.
class Something
{
private:
static int s_nValue;
};
int Something::s_nValue = 1;
int main(){
Something::s_nValue = 2; // Compiler error here.
}
Private still means the same thing: you cannot use the name Something::s_nValue except in the definition of a member of Something (or a friend, or a nested class within Something).
int Something::s_nValue = 1;
is the definition of a member of Something - namely, that static member s_nValue.
int Something::another_static_val = s_nValue; // also okay
int OtherClass::x = Something::s_nValue; // Illegal access!
int Something::getValue() const {
return s_nValue; // okay, getValue is a member of same class
}
int regularFunction() {
return Something::s_nValue; // Illegal access!
}
Does private even mean anything when we are talking about static members?
I'll try to answer with a classic example. Consider the following piece of code:
#include <iostream>
class foo {
static int count;
int id;
public:
foo() : id(++count) {}
int getid() const { return id; }
};
int foo::count = 0;
int main() {
foo f1, f2, f3;
std::cout << f1.getid() << std::endl;
std::cout << f2.getid() << std::endl;
std::cout << f3.getid() << std::endl;
}
LIVE DEMO
In the example above we use a private static int to count the instances of foo created. We made the count static member variable private because we don't want anyone else except object of type foo to mess with it.
And this is only a naive example, think of the possibilities.
Public, private and protected are properties of a class and not of an object. Their purpose is to let you specify which parts of this class are visible to other classes, and not to hide stuff from objects of the same class. So, you can write code like this :
class A
{
public:
bool operator<(const A& other)
{
return this->val < other.val;
}
private:
int val;
};
So, private makes sense even when applied to static members - it just says that other classes cannot see this member.

Member function called only on initialization of first instance of a class (C++)

I have a member function for a base class that I only want to be called [once] on the initialization of the first instance of the class (whether it be a direct instance of the base class, or an inherited class). Basically, I want to avoid unnecessary function calls.
A thing that is done only done during the first time something happens is the initialization of function local statics during the first execution of the surrounding function. So how you could do it:
class X {
static int firstInitFunc();
public:
X() {
static int onFirstCtorCall = firstInitFunc();
}
};
Now the first time you create an X, onFirstCtorCall will be initialized (threadsafe), calling the function. Any following creation of X won't call that function again.
If you have multiple constructors on X, you'll still want only one call to the function. You can achieve that by either delegating to the constructor with the static variable or by using another static function:
C++11:
class X {
static int firstInitFunc();
public:
X() {
static auto onFirstCtorCall = firstInitFunc();
}
X(int) : X() // delegate to X()
{ /* ... */ }
};
C++03:
class X {
static int firstInitFunc();
static void callFirstInit() {
static int onFirstCtorCall = firstInitFunc();
}
public:
X() {
callFirstInit();
}
X(int) {
callFirstInit();
}
};
Update: I'll pick up juanchopanza's comment and provide an example using std::call_once:
C++11 using call_once
class X {
static void firstInitFunc(); //see note to return types
static std::once_flag firstInitFlag;
public:
X() {
std::call_once(firstInitFlag, firstInitFunc);
}
X(int) {
std::call_once(firstInitFlag, firstInitFunc);
}
};
Note to return types: While in the case of function local statics' initialization used for the function call, that function must return a value, with wich the static will be initialized. In contrast, with std::call_once the function may not have a return type, because any returned value will not be evaluated.
Simple solution:
class C
{
private:
static bool runOnce;
public:
C()
{
if (!C::runOnce)
{
C::runOnce = true;
RunSth();
}
}
};
bool C::runOnce = false;

How access class variables in c++

Is it possible in c++ to access class variables in other classes without creating an object. I have tried to use static, but the other class doesnt recognize my variable.
I have 3 classes. In two of those the sae variables should be used. In the third class I am changing the values. Would be grateful if you could help. Maybe youve got an example.
class Myclass
{
public:
static int i;
};
int Myclass::i = 10;
class YourClass
{
public:
void doSomething()
{
Myclass::i = 10; //This is how you access static member variables
}
};
int main()
{
YourClass obj;
obj.doSomething();
return 0;
}
static is the right keyword here:
class A {
public:
static int i; // <-- this is a class variable
};
class B {
public:
void f() { A::i = 3; } // <-- this is how you access class variables
};
They only potential problem I can think of is that
You made the class variable protected or private, thus rendering it inaccessible from other code.
You forgot to specify the full scope of the class variable (with A:: in this example).
I think the Singleton Pattern would help, but I'm no big fan of it. A lot better design would be to have one class take ownership of the object, and pass references to this object to the other classes.
yes you can bro, try this
struct car{
string model;
string paint;
int price;
};
int main(){
// creates an object of the class car
car BMW;
// assign the values
bmw.model = "m sports";
bmw.paint ="red";
bmw.price = 24000;
}