#include <iostream>
using namespace std;
class MyClass
{
public:
void printInformation();
};
void MyClass::printInformation()
{
return;
}
int main()
{
MyClass::printInformation();
fgetc( stdin );
return(0);
}
How would I call the printInformation function within main?
The error tells me that I need to use a class object to do so.
Declare an instance of MyClass, and then call the member function on that instance:
MyClass m;
m.printInformation();
From your question it is unclear if you want to be able use the class without an identity or if calling the method requires you to create an instance of the class. This depends on whether you want the printInformation member to write some general information or more specific about the object identity.
Case 1: You want to use the class without creating an instance. The members of that class should be static, using this keyword you tell the compiler that you want to be able to call the method without having to create a new instance of the class.
class MyClass
{
public:
static void printInformation();
};
Case 2: You want the class to have an instance, you first need to create an object so that the class has an identity, once that is done you can use the object his methods.
Myclass m;
m.printInformation();
// Or, in the case that you want to use pointers:
Myclass * m = new Myclass();
m->printInformation();
If you don't know when to use pointers, read Pukku's summary in this Stack Overflow question.
Please note that in the current case you would not need a pointer. :-)
If you want to make your code work as above, the function printInformation() needs to be declared and implemented as a static function.
If, on the other hand, it is supposed to print information about a specific object, you need to create the object first.
declare it "static" like this:
static void MyClass::printInformation() { return; }
You need to create an object since printInformation() is non-static. Try:
int main() {
MyClass o;
o.printInformation();
fgetc( stdin );
return(0);
}
you have to create a instance of the class for calling the method..
On an informal note, you can also call non-static member functions on temporaries:
MyClass().printInformation();
(on another informal note, the end of the lifetime of the temporary variable (variable is important, because you can also call non-const member functions) comes at the end of the full expression (";"))
Related
So I have done some research, and have found you can create a boost::thread object and have it start with a non-static class function by using "this" and boost::bind etc. It really doesn't make much sense to me and all the examples I could find had the boost::thread object launched within the same class as the function it was starting with so this could be used. I however, am launching the thread in a different class so I'm afraid by using "this", I will be saying the "this" is from the class I am creating the thread from, rather than the one the function is in (I'm probably wrong, I need to learn more about this "this" guy). Here is an example of my source I am having the problem with.
ANNGUI.h
class ANNGUI
{
private:
boost::thread *GUIThread;
Main *GUIMain;
public:
// Creates the entire GUI and all sub-parts.
int CreateGUI();
}
ANNGUI.cpp
int ANNGUI::CreateGUI()
{
GUIMain = new Main();
GUIThread = new boost::thread(GUIMain->MainThreadFunc);
};
This isn't all the source, but I think my problem is in here somewhere, I know I have to deal with the "this" somehow, but I'm unsure how. I Could use a static function, but I didn't really want to make my variables static either.
Thanks.
Also, Is there any very good resource for using any boost libraries? Their web site documentation seems good, but over my head.
The this keyword is used with boost::bind when the function object you're creating is bound to a object member function. Member functions can't exist apart from instances, so when creating a functor object out of a member function with boost::bind, you need a pointer to an instance. That's exactly what the this keyword actually is. If you use the this keyword within a member function of a class, what you get is a pointer to the current instance of that class.
If you were to call bind from outside a class member function, you might say something like:
int main()
{
Foo f;
boost::thread* thr = new boost::thread(boost::bind(&Foo::some_function, &f));
}
Here, we're using Foo::some_function as our thread function. But we can't use this because we're calling bind from main. But the same thing could be achieved using this if we called bind from within a member function of Foo, like so:
void Foo::func1()
{
boost::thread* thr = new boost::thread(boost::bind(&Foo::some_function, this));
}
If a member function is static, or is simply a regular (non-member) function, then you don't need an instance pointer at all. You would just do:
boost::thread* thr = new boost::thread(some_regular_function);
As others mentioned, when you want to call an object method in a new thread, you have to supply the address of that object. But you don't need to call boost::bind, you can use the overloaded boost::thread constructor like this:
GUIThread = new boost::thread(&Main::MainThreadFunc, GUIMain);
If the method is in the same class you use this to get the address of the current instance, e.g.:
t = new boost::thread(&myclass::compute, this);
If the method has parameters, you can specify them after the second argument, e.g.:
t = new boost::thread(&myclass::compute, this, p1, p2);
boost::bind is your friend (it can sometimes have a rough way of showing it though)!
use GUIThread = new boost::thread(boost::bind(&Main::MainThreadFunc, GUIMain));
and then make your MainThreadFunc a regular member. That means that you can use the instance variables directly like you would normally do.
Something like this:
class GUIMain {
public:
GUIMain() : m_Member(42) {}
void MainThreadFunc() {
// use all members as you would normally do
std::cout << m_Member << std::endl;
}
private:
int m_Member;
};
In cases like this it is useful to think of non-static member functions as free functions that take the this as first parameter, for example in your case void MainThreadFunc(Main* this).
boost::thread accepts a nullary functor, so you have to pass it a nullary functor which contains a reference to the instance GUIMain and calls GUIMain->MainThreadFunc which, seen as I explained above, would be something like MainThreadFunc(GUIMain).
Boost (and now also C++ with TR1) provides helpers to create such functors, namely boost::bind (or alternatively boost::lambda::bind). The expression boost::bind(f, arg1, arg2, ...) means "return a nullary functor which calls f(arg1, arg2, ...)".
That said, you can use the following expression to create the thread:
GUIThread = new boost::thread(boost::bind(&Main::MainThreadFunc, GUIMain))
If your object is a functor, i.e. has an operator(), you can pass an instance of it to boost::thread. The operator() does not need to be static. For example:
#include <boost/thread.hpp>
struct th {
void operator()();
};
void th::operator()()
{
for (;;) {
// stuff
}
}
int main()
{
th t;
boost::thread my_thread( t ); // takes a copy of t !
my_thread.join(); // blocks
return 0;
}
Can the same function be defined differently for different objects of the same class??
in A.h
class Hello{
public:
void myfunction();
}
main.cpp
Hello B0,B1;
// Here I want to define the function 'myfunction' for each object differently
int main(){
B0.myfunction();
B1.myfunction();
}
Is this possible?
Not directly, and I'd wonder why you want to do that if you really do want them to be objects of the same class type? This is what inheritance and virtual functions are for! If you want them to behave differently, you should make them different (but related) classes.
That said, I can think of one way to achieve something like this. std::function.
Have a class member like std::function<void(Hello*)> myfunctionimpl;, and then a member function void myfunction() { myfunctionimpl(this); }
Then in the constructor of Hello, you can set myfunctionimpl as a pointer to some other function, or with a lambda. For example, the following:
#include <functional>
#include <iostream>
class Hello {
public:
typedef std::function<void(Hello*)> MyFunctionType;
private:
MyFunctionType myfunctionimpl; // this holds the customisable function object
public:
Hello(const MyFunctionType& mf) // construct with a custom function object passed in
: myfunctionimpl(mf)
{}
Hello() // construct with a default function object
: myfunctionimpl([](Hello *h) {
std::cout << "Default function called on " << h << '\n';
})
{}
Hello(int){} // dummy to leave function object unset
void myfunction() {
// call the function object, only if it is safe to do so
if (this->myfunctionimpl) {
this->myfunctionimpl(this);
}
else {
std::cerr << "myfunctionimpl not set!\n";
}
}
};
void freeFunction(Hello*)
{
std::cout << "freeFunction\n";
}
int main()
{
Hello h1; // default
Hello h2(1); // not set
Hello h3(freeFunction); // custom function
h1.myfunction();
h2.myfunction();
h3.myfunction();
}
prints:
Default function called on 0x7fffa12518e0
myfunctionimpl not set!
freeFunction
So here the member function myfunction behaves the same way for every instance; calls the myfunctionimpl function object (if it is set). But you can customise the function object that is called for each instance, since that is just class data.
The default constructor demonstrates use of lambdas, which allow you to write small functions in place, which is probably what you will want to do to provide custom behaviour when each object is constructed. There are lots of tutorials for lambdas, for instance.
No, a member function of all instances of the same class behave the same. However, the behaviour can depend on the state of the object. For example, you could store a function pointer in a data member and call the pointed function in the member function. So, the member function does exactly the same thing for each instance: calls the function pointed by the member, but the observed behaviour may be completely different if the pointed function is different.
Also, if the function is virtual, then instances of different subclasses can override the virtual function differently.
As from your comment
I am trying to create a kind of framework using c++ and opengl. Suppose i have a object of a class lets say Button which has a function onClick. On clicking button different users should be able to define the function in their own way.
See here for an excellent article by Herb Sutter on the subject of virtuality, since that is what you would look for when considering to build functionality described in your question and building framework.
The questions are old, but people still keep asking them,
One building framework could be interested on
Polymorphism pointers and class inheritance;
Virtual functions a member functions whose behavior can be overridden in derived classes.
I am trying to do something like this:
Create an object and bind its member functions to functions from a DLL. For example,
class A {
private:
int a;
public:
void func_a();
};
When loading from a DLL I want to create an A object, and set func_a to a function that is loaded from the DLL
A aObj;
(aObj.*func_a)() = getAdr(&s, h, "fmiGetTypesPlatform");
I do not know the syntax for it, but I mean I want to set the result of
getAdr(&s, h, "fmiGetTypesPlatform");
to an object's member function
Thanks in advance.
What you're looking for is a function pointer:
class A {
private:
int a;
public:
void (*func_a)();
};
Then, you can set this like any other pointer.
A aObj;
aObj.func_a = getAdr(&s, h, "fmiGetTypesPlatform");
Note that the referenced function, fmiGetTypesPlatform(), is a regular function. It is not a class method (i.e., no this, et al.), and it gets invoked via its function pointer.
(*aObj.func_a)();
If you know at compile time which DLL functions you want to use, you can make the class members one-line wrappers and encapsulate any data you need inside the object.
If you want to be able to assign arbitrary functions to class members, function pointers will work, with a little extra setup. Example code: http://goffconcepts.com/techarticles/calldll.html
Note that you can call a function pointer stored as a class member by name as if it were a function, with the usual object.func() syntax. In fact, this is how virtual member functions are implemented, under the hood.
If, however, the calls are not static, you still might want to put a wrapper around them so you can make the data they use private to your class.
I wrote the following code:
class A
{
public:
int cnt;
static void inc(){
d.cnt=0;
}
};
int main()
{
A d;
return 0;
}
I have seen this question:
How to call a non static member function from a static member function without passing class instance
But I don't want to use pointer. Can I do it without using pointers?
Edit:
I have seen the following question:
how to access a non static member from a static method in java?
why can't I do something like that?
No, there is no way of calling a non-static member function from a static function without having a pointer to an object instance. How else would the compiler know what object to call the function on?
Like the others have pointed out, you need access to an object in order to perform an operation on it, including access its member variables.
You could technically write code like my zeroBad() function below. However, since you need access to the object anyway, you might as well make it a member function, like zeroGood():
class A
{
int count;
public:
A() : count(42) {}
// Zero someone else
static void zeroBad(A& other) {
other.count = 0;
}
// Zero myself
void zeroGood() {
count = 0;
}
};
int main()
{
A a;
A::zeroBad(a); // You don't really want to do this
a.zeroGood(); // You want this
}
Update:
You can implement the Singleton pattern in C++ as well. Unless you have a very specific reason you probably don't want to do that, though. Singleton is considered an anti-pattern by many, for example because it is difficult to test. If you find yourself wanting to do this, refactoring your program or redesigning is probably the best solution.
You cannot use non-static member variables or functions inside a static function without using pointers.
You don't need a pointer per se, but you do need access to the object through which you are accessing the non-static variable. In your example, the object d is not visible to A::inc(). If d were a global variable rather than a local variable of main, your example would work.
That said, it's curious why you'd want to go to any great effort to avoid using pointers in C++.
So I have done some research, and have found you can create a boost::thread object and have it start with a non-static class function by using "this" and boost::bind etc. It really doesn't make much sense to me and all the examples I could find had the boost::thread object launched within the same class as the function it was starting with so this could be used. I however, am launching the thread in a different class so I'm afraid by using "this", I will be saying the "this" is from the class I am creating the thread from, rather than the one the function is in (I'm probably wrong, I need to learn more about this "this" guy). Here is an example of my source I am having the problem with.
ANNGUI.h
class ANNGUI
{
private:
boost::thread *GUIThread;
Main *GUIMain;
public:
// Creates the entire GUI and all sub-parts.
int CreateGUI();
}
ANNGUI.cpp
int ANNGUI::CreateGUI()
{
GUIMain = new Main();
GUIThread = new boost::thread(GUIMain->MainThreadFunc);
};
This isn't all the source, but I think my problem is in here somewhere, I know I have to deal with the "this" somehow, but I'm unsure how. I Could use a static function, but I didn't really want to make my variables static either.
Thanks.
Also, Is there any very good resource for using any boost libraries? Their web site documentation seems good, but over my head.
The this keyword is used with boost::bind when the function object you're creating is bound to a object member function. Member functions can't exist apart from instances, so when creating a functor object out of a member function with boost::bind, you need a pointer to an instance. That's exactly what the this keyword actually is. If you use the this keyword within a member function of a class, what you get is a pointer to the current instance of that class.
If you were to call bind from outside a class member function, you might say something like:
int main()
{
Foo f;
boost::thread* thr = new boost::thread(boost::bind(&Foo::some_function, &f));
}
Here, we're using Foo::some_function as our thread function. But we can't use this because we're calling bind from main. But the same thing could be achieved using this if we called bind from within a member function of Foo, like so:
void Foo::func1()
{
boost::thread* thr = new boost::thread(boost::bind(&Foo::some_function, this));
}
If a member function is static, or is simply a regular (non-member) function, then you don't need an instance pointer at all. You would just do:
boost::thread* thr = new boost::thread(some_regular_function);
As others mentioned, when you want to call an object method in a new thread, you have to supply the address of that object. But you don't need to call boost::bind, you can use the overloaded boost::thread constructor like this:
GUIThread = new boost::thread(&Main::MainThreadFunc, GUIMain);
If the method is in the same class you use this to get the address of the current instance, e.g.:
t = new boost::thread(&myclass::compute, this);
If the method has parameters, you can specify them after the second argument, e.g.:
t = new boost::thread(&myclass::compute, this, p1, p2);
boost::bind is your friend (it can sometimes have a rough way of showing it though)!
use GUIThread = new boost::thread(boost::bind(&Main::MainThreadFunc, GUIMain));
and then make your MainThreadFunc a regular member. That means that you can use the instance variables directly like you would normally do.
Something like this:
class GUIMain {
public:
GUIMain() : m_Member(42) {}
void MainThreadFunc() {
// use all members as you would normally do
std::cout << m_Member << std::endl;
}
private:
int m_Member;
};
In cases like this it is useful to think of non-static member functions as free functions that take the this as first parameter, for example in your case void MainThreadFunc(Main* this).
boost::thread accepts a nullary functor, so you have to pass it a nullary functor which contains a reference to the instance GUIMain and calls GUIMain->MainThreadFunc which, seen as I explained above, would be something like MainThreadFunc(GUIMain).
Boost (and now also C++ with TR1) provides helpers to create such functors, namely boost::bind (or alternatively boost::lambda::bind). The expression boost::bind(f, arg1, arg2, ...) means "return a nullary functor which calls f(arg1, arg2, ...)".
That said, you can use the following expression to create the thread:
GUIThread = new boost::thread(boost::bind(&Main::MainThreadFunc, GUIMain))
If your object is a functor, i.e. has an operator(), you can pass an instance of it to boost::thread. The operator() does not need to be static. For example:
#include <boost/thread.hpp>
struct th {
void operator()();
};
void th::operator()()
{
for (;;) {
// stuff
}
}
int main()
{
th t;
boost::thread my_thread( t ); // takes a copy of t !
my_thread.join(); // blocks
return 0;
}