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)
Related
I'm running into syntax errors with C++ where I have to return a pointer to a function inline.
struct Note{}
Observer.hpp
class Observer {
protected:
void (*notify)(Note *note); // should this be *(*notify...)?
public:
void (*(*getNoteMethod)())(Note *note);
};
Observer.cpp
void (*Observer::getNoteMethod())(Note*) { //error: non-static data member defined out-of-line
return this->notify;
}
I'm getting this error, error: non-static data member defined out-of-line
I'm new to C++ and attempting to define the return function signature correctly.
The problem is the declaration syntax for the member function (which returns function pointer). Declare it as:
class Observer {
protected:
void (*notify)(Note *note);
public:
void (*getNoteMethod())(Note *note);
};
Better to declare the function pointer type in advance via using or typedef, which looks much clearer. E.g.
class Observer {
using function_pointer_type = void(*)(Note*); // the function pointer type
protected:
function_pointer_type notify; // the data member with function pointer type
public:
function_pointer_type getNoteMethod(); // the member function returns function pointer
};
// Out-of-class member function definition
Observer::function_pointer_type Observer::getNoteMethod() {
return this->notify;
}
My problem is about passing a member function from a Class A, to a member function of a Class B:
I tried something like this :
typedef void (moteurGraphique::* f)(Sprite);
f draw =&moteurGraphique::drawSprite;
defaultScene.boucle(draw);
moteurGraphique is A class, moteurGraphique::drawSprite is A member function,
defaultScene is an instance of B class, and boucle is B member function.
All that is called in a member function of A:
void moteurGraphique::drawMyThings()
I tried different ways to do it, that one seems the more logical to me, but it won't work!
I got:
Run-Time Check Failure #3 - The variable 'f' is being used without being initialized.
I think I am doing something wrong, can someone explain my mistake ?
C++11 way:
using Function = std::function<void (Sprite)>;
void B::boucle(Function func);
...
A a;
B b;
b.boucle(std::bind(&A::drawSprite, &a, std::placeholders::_1));
Member functions need to be called on objects, so passing the function pointer alone is not enough, you also need the object to call that pointer on. You can either store that object in the class that is going to call the function, create it right before calling the function, or pass it along with the function pointer.
class Foo
{
public:
void foo()
{
std::cout << "foo" << std::endl;
}
};
class Bar
{
public:
void bar(Foo * obj, void(Foo::*func)(void))
{
(obj->*func)();
}
};
int main()
{
Foo f;
Bar b;
b.bar(&f, &Foo::foo);//output: foo
}
Can't you make drawMyThing a static function if you don't need to instantiate A, and then do something like :
defaultScene.boucle(A.drawMyThing(mySpriteThing));
?
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.
There is such code:
void foo(void (*fun_ptr)()){
}
class B{
public:
B(){
foo(some_fun);
}
void some_fun(){}
};
Compilation error:
error: argument of type ‘void (B::)()’ does not match ‘void (*)()’
How to point to member function in this case? I cannot change declaration of function foo, only class B!
Declare B::some_fun() as static as there is an implicit this pointer passed as an argument to member functions. Note that making B::some_fun() static prevents access to non-public non-static members of B.
This a FAQ in it's own right.
There is no other solution than to wrap the member function in a static function and somehow tell it about the object instance to invoke the method on:
struct X { void foo(); }
void take_callback(void (*fun_ptr)())
{
fun_ptr(); // invoke callback
}
//wrap the method
X* instance = 0;
void wrap_memberfun()
{
if (instance) instance->foo(); // delegate
}
int main()
{
X x;
take_callback(&X::foo); // doesn't compile
// workaround:
instance = &x;
take_callback(&wrap_memberfun);
}
some_fun() is a member function and needs an object. Make some_fun() static.
static void some_fun() {};
To invoke non-static member function you need two pointers (function and class instance), so you can't really use pointer to a non-static member where you expect pointer to a function.
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. */
}