I thought I cannot use a static pointer to call a non-static function, since I think a static pointer belongs to the whole class but non-static function belongs to a specific object. But somehow I made it succeed and am not sure why this is so.
Here is my code:
#include <cstdio>
class B
{
public:
void show(int aValue);
};
//B.cpp
void B::show(int aValue)
{
if (aValue == 100)
printf("This is the desired value");
else
printf("This is not the desired value");
}
class A
{
private:
static B* mUpdater;
public:
static int function1();
};
B* A::mUpdater = new B();
int A::function1()
{
int final = 100;
mUpdater->show(final); // mUpdater is a static pointer, show is a non-static function
return 1;
}
int main()
{
return !A::function1();
}
The code runs, and prints "This is the desired value". But I am a little bit confused since I thought the code cannot run. Is this because I assign the address of a specific object to the pointer so that It can work? Or no matter in which case, static pointer can just call non-static functions?
Any idea will be more than appreciated.
mUpdaterisstaticallows you to useA::mUpdaterwithout an instance ofA. Its usage afterward is identical.Ainherit fromB?show(1);insidefunction1won't work). As long as you have a valid object, how or where that object is stored doesn't matter.