Access non static data member outside class - c++

Is it possible to access non static data members outside their class? Say you have an example like the following. I know it does not make much sense as an example, but I just want to understand how to access a non static data member. If the following is compiled it generates an error:
C.h|70|error: invalid use of non-static data member ‘C::age’|
//C.h
class C{
public:
int age;
};
int getAge();
//C.cpp
C::C()
{
age = 0;
}
int getAge(){
return (C::age);
}

Non-static members are instance dependent. They are initialized when a valid instance is initialized.
The problem with your example is that, it tries to access a non-static member through the class interface without first initializing a concrete instance. This is not valid.
You can either make it static:
class C{
public:
static int age;
};
which requires you to also define age before using at runtime by: int C::age = 0. Note that value of C::age can be changed at runtime if you use this method.
Or, you can make it const static and directly initialize it like:
class C{
public:
const static int age = 0;
};
In this case, value of C::age is const.
Both of which will let you get it without an instance: C::age.

Without making it static, you would have to create a value:
Either an lvalue:
C c;
return c.age;
or an rvalue:
return C().age;
// or
return C{}.age;
The problem with your code is that you try to access the age member without creating an instance of the class. Non-static data members of a class are only accessible through an instance of the class, and in your case no instance is created.

The reason why you can't is because local variables are allocated at runtime onto the stack - you can obtain its position if you really wanted to with some inline asm but it would require some debugging to obtain the stack position and the later (after the function) you want to access it the more likely it will have long been overwritten by something else.

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

C++ - How to access private members of a class, from a static function of the same class?

What I have:
So I have a class with a private member, and a static function.
The function must really be static and I can't change that.
What I want:
I need to access, from the static function, the private member.
Any ideas? :)
Please check the code bellow:
class Base
{
private:
int m_member;
public:
Base() : m_member(0) {};
~Base() {};
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); /* This must really be static because it is coming from C */
};
void Base::key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
m_member = 1; // <---- illegal reference to non-static member 'Base::m_member'
}
Static member functions are part of the class, and have no object instance associated with them (in other words, there's no this pointer in static member functions). To be able to access non-static member variables you need an actual instance of the class.
A common solution when setting callbacks using old C libraries, is to use some kind of user-data pointer, and assign it to an instance of the class. Fortunately for you, the GLFW library have such a pointer that you can use.
A static member function cannot access a non-static member (unless it creates its own local instance the non-static member would belong to).
This is because non-static members belong to an instance of the class, and the static member does not. Think about it: If you wrote
Base::callback(...);
what m_member should this access? There simply is no instance of Base and thus not m_member.
You can't. You need an instance to get to the non-static private. In the static method you don't have an instance available.
So you need some way to get an instance, either by passing it to the static method, or by being able to get it from somewhere else. But in that case, you could as well make it a non-static method.
You could make m_member
static int m_member;

Class static method access to it's static data members

This question is an extension to:
Class method access to it's data members
The take away from the question was that whenever a class method is called, it is implicitely passed the address of the object which helps it access the data members of the class using a 'this*'.
The follow up question is:
How are the static methods of the class able to access the static data members of the class?
The argument remains the same. A function can only access the local variables loaded on the stack.
Are the static data members or their address loaded onto the static function stack implicitely?
If no, how does it work?
The reason is because both are not bound to an instance of that class.
For e.g.
class test
{
public:
static int i=5;
static int getI(){return i;}
};
You can access i like:
int a=test::i;
or like
int a=test::getI();
i is stored in the global data part of the program. It is not bound to an object, therefore it is also identical for every instance created. You can access i without create an instance of class test. class test merely a namespace in this situation. There is no memory magic.

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

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