Static member object of a class in the same class - c++

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;}

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

Does a static member inside a nested class have static duration for the enclosing class?

If I have nested classes, and these nested classes have static members, will those members still be static for the enclosing class? For example, if I have
class Enclosing {
public:
Enclosing();
private:
class Nested {
public:
Nested();
private:
static int thing;
};
};
If I do
auto A = Enclosing();
auto B = Enclosing();
Will A and B be able to have different values for thing?
Will A and B be able to have different values for thing?
No they won't have different values. All instances will see the same value for thing; the nesting of the class has no impact here.
static member variables are "associated with the class" (i.e. over non-static members that are associated with the instances of the class). From cppreference;
Static data members are not associated with any object. They exist even if no objects of the class have been defined. If the static member is declared thread_local (since C++11), there is one such object per thread. Otherwise, there is only one instance of the static data member in the entire program, with static storage duration.
Live sample.

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".

Change Static Variable Scope

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.

non-static vs. static function and variable

I have one question about static and non-static function and variable.
1) non-static function access static variable.
It's OK!
class Bar
{
public:
static int i;
void nonStaticFunction() {
Bar::i = 10;
}
};
int Bar::i=0;
2) non-static function access non-static variable
Definitely OK!
3) static function access static variable&funciton
Definitely OK!
4) static function access non-static function
It's OK
class Bar
{
public:
static void staticFunction( const Bar & bar)
{
bar.memberFunction();
}
void memberFunction() const
{
}
}
5) static function access non-static variable
It's OK or not OK? I am puzzled about this!
How about this example
class Bar
{
public:
static void staticFunction( Bar & bar)
{
bar.memberFunction();
}
void memberFunction()
{
i = 0;
}
int i;
};
static function access non-static
variable
It's OK or not OK? I am puzzled about
this!
When called, a static function isn't bound to an instance of the class. Class instances (objects) are going to be the entities that hold the "non-static" variables. Therefore, from the static function, you won't be able to access them without actually being passed or storing elsewhere a specific instance to operate on.
So yes, the code in your last example is valid, because you are passed in an instance. However, you could not do:
static void staticFunction()
{
// error, this function is static, and is therefore
// not bound to a specific instance when called
i = 5;
}
Static means this is independent of a particular instance of the class. Static methods don't have access to the this pointer. That is the reason you need to call them using the class name.
When you call the Static method, you might not even have any instance of the class defined.
non-static means implies an instance, and could be different with different instances.
So, basically, it does not make sense to access non-static members from static methods.
For this, you need to understand what is static.
Static data members exist once for the entire class, as opposed to non-static data members, which exist individually in each instance of a class. They will have a class scope and does not bound to an instance of the class.
To access static member of the class, we use the format as below
::
if you have created 10 objects of a class.
Assume, you were able to access the non-static variable in the static member of the class, When the static function is called, which object's member it needs to change?
It's not ok. Static functions are accessible without having an instance of a class and thus can't access information that you would need an instance to determine.
For example, you don't need a car to know how many wheels it has, blueprints for a general car would suffice (that could be static information) but you can't tell what color the car is unless you're referring to a specific car (that information needs a specific instance of an object.)