quick question about static function in c++ - c++

static function in c++
SO, there can be only one instance of static function for this class. Right?

In C++, a static member function is just like a normal, global function, except with respect to visibility of names:
The name of the function is qualified with the class name.
Like a friend function, a static member function has access to private and protected class members. Also like a friend function, however, it does not have a this pointer, so it only has access to those parts of objects to which you've given it access (e.g., passed as a parameter).
(Thanks Alf): You can't declare any member function (static or otherwise) as extern "C".

A static member function (inside a class) means that you can call that function without creating an instance of the class first. This also means that the function cannot access any non-static data members (since there is no instance to grab the data from).
e.g.
class TestClass
{
public:
TestClass() {memberX_ = 10;}
~TestClass();
// This function can use staticX_ but not memberX_
static void staticFunction();
// This function can use both staticX_ and memberX_
void memberFunction();
private:
int memberX_;
static int staticX_;
};

Making a function static allows it to be called without instantiating an instance of the class it belongs to. learncpp.com has some more on the subject and check out the following example which will fail to compile:
class Foo
{
public:
static void Bar1();
void Bar2();
};
int main(int argc, char* argv[])
{
Foo::Bar1();
Foo x;
x.Bar2();
Foo::Bar2(); // <-- error C2352: 'Foo::Bar2' : illegal call of non-static member function
return 0;
}

Static functions can be called without actually creating a variable of that type, e.g.:
class Foo
{
public:
static void Bar();
void SNAFU();
};
int main( void )
{
Foo::Bar(); /* Not necessary to create an instance of Foo in order to use Bar. */
Foo x;
x.SNAFU(); /* Necessary to create an instance of Foo in order to use SNAFU. */
}

Related

Can you put a function inside of another function in c++?

Say I have two functions, and one calls the other to work.
void friendList::addFriend(string userNameIn)
{
if(friendList::isFriend(userNameIn))
//add friend
}
bool friendList::isFriend(string name)
{
//check if user name exists
}
Is this allowed? I am getting errors for:
In member function 'void User::addFriend(std::string)':
and error: cannot call member function 'bool friendList::isFriend(std::string)' without object
Is it because the functions aren't completely filled out yet?
Yes, functions can of course call other functions in C++.
Doing so is not a case of functions being put inside other functions: your question title is misleading.
It looks as if addFriend might be a static member function, and as such it has no object, whereas isFriend is a non-static member function. When a static member function of a class calls a non-static member function, it must supply an object:
class someclass {
// ...
static void static_member();
void nonstatic_member();
};
void some_class::static_member()
{
nonstatic_member(); // error
some_instance.nonstatic_member(); // okay
}
void some_class::nonstatic_member()
{
}
static_member cannot call nonstatic_member, but it can invoke nonstatic_member on an object. It will work provided that some_instance is suitably defined somewhere as an instance of some_class.
The compiler error:
cannot call member function [...] without object
Suggests to me that you are trying to call a non-static member function directly, rather than through an object. For example:
class Foo
{
public:
int DoIt() {}
};
int main()
{
Foo::DoIt();
}
If that's what you're trying to do, you can't. Non-static member functions need to be called through an object:
int main()
{
Foo foo;
foo.DoIt();
}
If you must refrain from calling through an object, then you need to make the member function static:
class Foo
{
public:
static int DoIt() {}
};
int main()
{
Foo::DoIt(); // OK
}
But then, DoIt won't be able to call other non-static member functions.
You want to use the 'this' pointer. this->isFriend(userNameIn)

Private static variable

Why we have to declare static member function to access private static variable? Why not simply use a public function to access s_nValue? I mean why is it better to use static member function instead of a non-static public function?
class Something
{
private:
static int s_nValue;
};
int Something::s_nValue = 1; // initializer
int main()
{
}
Why we have to declare static member function to access private static variable?
You don't have to:
class Something
{
private:
static int s_nValue;
public:
static int staticAccess() { return s_nValue; }
int Access() { return s_nValue; }
};
int Something::s_nValue = 1; // initializer
int main()
{
Something s;
Something::staticAccess();
s.Access();
return 0;
}
Both methods work as can bee seen here
That being said, it doesn't really make sense to make a non-static member function to access a static variable (as you would need an instance of the class to be able to call it).
If you use pubilc function , you have to call it using an object, and it's not appropriate to call a static function with object, so better to keep it in static method which can be accessible directly through "classname::"
Why we have to declare static member function to access private static variable?
You don't have to. You can access a private static member from any member function, static or otherwise. You can also access it from any friend function, or member function of a friend class.
Why not simply use a public function to access s_nValue?
Because that's less simple than a static function. You need an object to call a non-static member function; why not simply allow access to the static variable without creating an object?

Void Pointers with Inherited Classes

I have a class, A, which requires static event handlers. I needed the static event handlers because an interrupt is calling the event handler.
class A {
private:
static void (*fn1)();
public:
A();
static void setFn1(void (*function)(void));
static void onEvent();
};
A::A() { }
void A::setFn1(void (*function)(void)) {
fn1 = function;
}
void A::onEvent() {
A::fn1();
}
I want to inherit A based upon the application and create the event
handler logic in the child, using fn2 here.
class B : public A{
public:
B();
void fn2();
};
B::B() {
A::setFn1(&fn2);
}
void B::fn2() {...}
When I call: A::setFn1(&fn2) I get the following compiler error.
#169 argument of type "void (B::)()" is incompatible with parameter of type "void ()()
My mind is all loopy with these void-pointers and I do not know if I am even using the proper design anymore. The A class contains all my utility methods. The B class contains my application specific functionality.
A non-static member function is not a free function, the types differ. You cannot use a non-static member function as if it was a pointer to a function:
struct test {
void foo();
static void bar();
};
&test::foo --> void (test::*)()
&test::bar --> void (*)()
I won't go in as much as recommending changing the function to be static as I don't find the current design particularly useful. But you can take this and try to rethink a design that will make more sense. (A single callback function for all the process? Why inheritance at all? A user-defined constructor that does the same as the compiler generated? In a class that should not be instantiated?...)
When I call: A::setFn1(&fn2) I get the following compiler error.
fn2 is a member function of a B, so you have to qualify its name:
A::setFn1(&B::fn2)
// ^^^
Moreover, fn2 should be static, because non-static member functions actually work on an implicit this pointer, so they are accepting an argument:
class B : public A{
public:
B();
static void fn2();
// ^^^^^^
};
With these two changes, your program should compile.

Declaring C++ static member functions as friends of the class in which it resides (syntax)

What is the syntax for declaring a static member function as a friend of the class in which it resides.
class MyClass
{
private:
static void Callback(void* thisptr); //Declare static member
friend static void Callback(void* thisptr); //Define as friend of itself
}
Can I fold it into this one-liner?
class MyClass
{
private:
friend static void Callback(void* thisptr); //Declare AND Define as friend
}
Is there another way to fold it all into a single line?
Answer
Please don't downvote, this stems from my lack of knowledge about C++ static member functions. The answer is that they don't need to be friend, they already can access private members. So my question was somewhat invalid.
Actually, no need to use friend if it is static is more accurate. A static member function has access to the internals of the class just like a normal member function. The only difference is it doesn't have a this pointer.
void MyClass::Callback(void* thisptr) {
MyClass* p = static_cast<MyClass*>(thisptr);
p->public_func(); // legal
p->private_func(); // legal
p->private_int_var = 0; // legal
}
The class member function cannot be a friend of its own class - its already the class member and can access its privates. What' the point in befriending it? Its not Facebook...
A static member function has access to the protected / private parts of a class by default, no need to make it a friend.
#include <iostream>
struct Foo{
Foo(int i) : an_int(i) {}
static void print_an_int(Foo& self){
std::cout << self.an_int;
}
private:
int an_int;
};
int main(){
Foo f(5);
Foo::print_an_int(f); // output: 5
}

Why can I call the private constructor from ?global scope?

this code compiles and runs without errors:
class foo{
static foo *ref;
foo(){}
public:
static foo *getRef(){
return ref;
}
void bar(){}
};
foo* foo::ref = new foo; // the construcrtor is private!
int main(int argc, const char *argv[])
{
foo* f = foo::getRef();
f->bar();
return 0;
}
could somebody explain why can the constructor be called?
That scope isn't global - static members are at class scope, and so their initialization expression is also at class scope.
The answer is that it is not available in the global scope. The initializer of a static member is defined to be inside the class scope, so it has access to the private members.
ยง9.4.2/2 [...]The initializer expression in the definition of a static data member is in the scope of its class (3.3.6).
This form of initialization of static members are not necessary in older c++. They are made compulsary in later release of c++.
And, this form of static member initialization will generally used to initialize the static members before creation of any class objects.
(E.g) int MyClass::objectsCounter=0;
But by,
foo* foo::ref = new foo;
this statement you are just initializing a static member (which is of pointer type) by creating a new object.
And in this case you are intializing a private member by calling a private method of its own class.
Hence there is no role of globe scope here.