Change Static Variable Scope - c++

I have in one C++ class a definition of static variable:
static SomeType MyClass::StaticVariable;
In another class I want to use this variable without MyClass prefix. Can I do that? How?

You could use a reference:
class MyOtherClass {
static SomeType &StaticVariable = MyClass::StaticVariable;
// ...
}
You will have to ensure that you don't try to reference MyOtherClass::StaticVariable before MyClass::StaticVariable has been constructed (at program startup).

You can do that only if that "another class" is derived from MyClass and StaticVariable has either public or protected visibility. Alternatively, you can move that member variable to some other scope or declare a reference/pointer and point it to that variable so that later you have to do less typing.

Related

Initialize a private static field outside the class (the meaning of private in this case) and calling to static functions

If I will define a private static field in class. Given that it's a private field, can't I initialize it outside the class?
class X{
static int private_static_field;
public:
static void setPrivateStaticField(int val);
};
void X::setPrivateStaticField(int val) {
private_static_field = val;
}
int X::private_static_field(0); // something like that it's ok? if yes, I must write this line? why? can I write it in main?
It's look that it's ok (according to the compiler), but if so, I don't understand the concept of private - How it's ok if it's outside the class?
In addition, given the class above, and the next code:
int main() {
X x1();
x1.setPrivateStaticField(3);
return 0;
}
What is the meaning of x1.setPrivateStaticField(3); , after all, this function is static and hence it's not related to some object.
Hence, I don't understand how it's ok to call setPrivateStaticField with object (x1) ?
(I thought that just X::setPrivateStaticField(3); will be ok and that x1.setPrivateStaticField(3); will be error)
I don't understand the concept of private - How it's ok if it's outside the class?
There is no contradiction here. Prior to C++ 17 static member variables required a definition that is placed separately from the class declaration.
Despite the fact that the text of the definition is placed outside the class, the member variable remains part of the class where it is declared, and retains its accessibility according to its declaration inside the class. This includes private accessibility.
What is the meaning of x1.setPrivateStaticField(3); , after all, this function is static and hence it's not related to some object.
Although C++ compiler lets you call static member functions on the object, it is cleaner to call them using scope resolution operator :: and the class name:
X::setPrivateStaticField(3);
Allowing or disallowing class method calls on an instance is up to the designers of the language. C++ designers decided to allow it; designers of other programming languages disallow it, or require compilers to issue a warning.
Within a class definition static data members are declared but not defined. So they even can have an incomplete type.
So this record
int X::private_static_field(0);
is a definition of the static data member declared in the class definition like
class X{
static int private_static_field;
// ...
This record
x1.setPrivateStaticField(3);
means an access to a class member. Static members are also class members. Using this access method the compiler will know to search the name setPrivateStaticField in the class definition because the name x1 defines an object of the class X.
Another way to access a static member is to use the following record
X::setPrivateStaticField

Static initialization with private constructor

In a class I have a static member that represents the singleton instance of that class:
class A {
public:
static const std::shared_ptr<A> INSTANCE;
private:
A();
};
In order to prevent more instances I made the constructor private. Now I have trouble to initialize the static var, because the initializer cannot access a private member. Here's the code I use in the .cpp file:
const std::shared_ptr<A> A::INSTANCE = std::make_shared<A>();
A factory method wouldn't help either, as it would have to be public as well. What else can I do to make this work? Note: I'd like to avoid the typical static get() method if possible.
You can't use make_shared, but you can just create the instance directly:
const std::shared_ptr<A> A::INSTANCE { new A };
The initialization of a static member is unrelated to the constructor, so the global statement is indeed the right way to go. Is it not working for you?
EDIT: I just realized you're trying to avoid using a singleton access method for some reason. Sounds suspiciously like the Borg pattern. :) Unrelated to you r specific question but I'd advise you to reconsider.

Declare class variable within class methods in C++

In python we may use self keyword to declare class variables within a member function of the class which can be subsequently used by other member functions of the class.
How to do such a thing in C++.
Python Code:
class abc():
{
def __init__(self):
self.help='Mike' #self.help is the class variable and can be used in other methods
def helpf():
morehelp=self.help+' Bike'
}
C++ code:
class abc
{
public:
abc();
public:
void helpf(void);
};
abc::abc()
{
string help="Mike";
}
void abc::helpf()
{
string morehelp=this->helpf+" Bike";// this keyword sounded like the one but...
}
There is no way to do such thing in C++.
You should declare members in class, not in functions.
You cannot declare class members inside functions in C++. You have to declare them outside functions, like in JAVA
class abc
{
public:
int publicInt; // This is a public class variable, and can be accesed from outside the class
int abc();
private:
float privateFloat; // This is private class variable, and can be accesed only from inside the class and from friend functions
void helpf(void);
};
that is not possible. Declaring variables inside a member function are local to that member function. If you want to use variables in your member function you have to declare class variables.
This works in Python because Python allows you to add a attribute to an object from anywhere simply by assigning to it. It attaches to that object, rather than the object's class. In keeping with Python's dynamic language philosophy, and particularly with its lack of variable declarations, all of this - including the decision about which attributes do or don't exist - happens at run time.
C++'s explicitly does not have a concept of one particular object having an attribute - all member variables are associated with the class, even if they take independent values on each instance. The set of all possible member variables, and which types they hold, is shared class-wide and set in stone at compile time. Because of this, what you're asking for basically doesn't make sense in C++.

Importance of static object in a class and how they are different from general object

#include "B.h"
class A
{
public :
A()
{
s_b = new B();
b = new B();
}
static B *s_b;
B *b;
};
#include<iostream>
using namespace std;
#include "A.h"
int main()
{
cout<<"hello";
}
In my project I have seen static object as above. But not able to know what is the exact use of it and how they are different from general object.
Please help me in finding out what I can do with s_b which is not being done by b.
For one, s_b doesn't take up memory for each instance of A that is created, whereas b does. The sizeof(A) is increased by b, but not by s_b.
A static is shared between all instances of the class, so it acts like a global. You don't need an object to access it, you can use A::s_b directly.
The only real difference between a static member and an object or function defined at namespace scope is access. A static data member can be private, for example, in which case it cannot be accessed outside of the class; and a static function member can access private data members, which a function at namespace scope cannot.
The access syntax is also different: if outside the class, you must use ClassName::memberName (or classInstance.memberName) to access the member. There is no using which can make it accessable otherwise.
generally speaking static members have to be initialized outside the declaration of the class except for constant int type if you are not using C++11.
So your code posted above is flawed. you need a statement like
A::s_b = B();
outside the class A { ... }; To initialize an static member inside an non static constructor is wrong because the constructor is used to construct an object but the static member
does not belong to the object but belong to the class. So these static members can not be modified through static member functions.
Think "class" as "human being" and an object of that "class" as a specific person, like "John Smith". So if you have a field, "salary". That should be a non-static field since each person has a different salary. But if you have field, "total_population", which should be a static member because this field semantically does not belong to one specific person but to the whole "human being".

Static member object of a class in the same class

Suppose we have a class as
class Egg
{
static Egg e;
int i;
Egg(int ii):i(ii) {}
Egg(const Egg &); //Prevents copy-constructor to be called
public:
static Egg* instance() {return &e}
};
Egg Egg::e(47);
This code guarantees that we cannot create any object, but could use only the static object. But how could we declare static object of the same class in the class.
And also one thing more since e is a static object, and static objects can call only static member functions, so how could the constructor been called here for static object e, also its constructors are private.
But how could we declare static object of the same class in the class.
A static member variable is not stored inside each object of a class. So if you declare a static member variable inside a class or as a namespace level object after you defined the class, differs only in respect to access (Class::var and var) and access to protected and private members.
And also one thing more since e is a static object, and static objects can call only static member functions
I think you are mixing static functions and static objects. Inside a static function you can call only static functions (unless you are calling them on an object).
so how could the constructor been called here for static object e
Like for every other object a constructor has to be called for static objects, too.
also its constructors are private
Access Control is checked on class level in C++. So since the static object is inside the class, it can access private members.
Unlike in some other languages, the following is legal in C++, since the access to a private member is from inside the class - even if on another object (other in this case):
class Test {
private:
int i;
public:
Test(const Test &other)
: i(other.i)
{}
};
But how could we declare static object of the same class in the class.
Normally you'd need a forward reference, but since Egg e is static, it's actually defined outside of the class definition. If e was not static, you'd get an error (something like "field Egg e has incomplete type").
And also one thing more since e is a static object, and static objects can call only static member functions, so how could the constructor been called here for static object e.
This is not quite true. A static member function within a class can only access static member data. static Egg e is an instance of Egg, so it can access all the members and data a regular Egg can.
also its constructors are private.
Any private member can be used from within a class. Since static Egg e is declared as a member of Egg, it can use the private constructor. The definition of e is outside the class since it's static, but it is still a class member.
And lastly your code doesn't compile because you left out a semicolon here:
static Egg* instance() {return &e;}