Set reference of function to non-static function from other c++ file - c++

I'm trying to set a reference of a non-static function in c++. The function I'm referencing is not from the same c++ file, and I get and error saying :
Cannot create a non-constant pointer to member function.
Main.cpp
#include <iostream>
#include "Test.hpp"
class testClass {
public:
void (*update) (void);
};
int main() {
testClass tc;
test t;
tc.update = &t.update; //This is where the error occurs
return 0;
}
Test.hpp
#ifndef Test_hpp
#define Test_hpp
#include <stdio.h>
class test {
public:
void update() {
//Do something
}
};
#endif /* Test_hpp */
My question is how do you do this without setting update in test class to static?
static void update() {
//Do something
}
Using this code it works, but like I've stated I do not want this functiont to be static.
EDIT :
Because I'm stupid I failed to mention that the class test should be able to be different. Also to the answers I got already I learned that tc.update = &t.update; is wrong.
For Example :
#include <iostream>
#include "Test.hpp"
#include "anotherTestClass.hpp"
//I do not want to use templates if possible
class testClass {
public:
void (*update)(void);
};
int main() {
testClass tc;
test t;
tc.update = &test.update; //I know this is wrong now.
testClass tc2;
anotherTestClass atc;
tc2.update = &atc.update;
//p.s. I'm bad with c++
}
And the error i get now is.
Assigned to 'void (*)()' from incompatible type 'void (test::*)()'
One more thing is I'm using XCode to program, which I believe uses LLVM-GCC 4.2 as the compiler.

class test {
public:
void update() {
//Do something
}
};
class testClass {
public:
void (test::* update) (void);
};
int main() {
testClass tc;
test t;
tc.update = &test::update;
return 0;
}

Your approach is essentially wrong.
Member Function Pointers.
The member in the testClass:
void (*update) (void);
is a function pointer, which is different to a method function pointer. That why in order to compile you should switch to a static method (which is essentially a "normal" function).
A method function pointer should containt the static information about the class the method belongs.
Practically the right way is:
void (test::* ptr_method)(void); // a member pointer to test class
In that way the variable named ptr_method is a method of the class test pointer.
Then,
Get the Address of a method.
Your statement:
tc.update = &t.update; //This is where the error occurs
is simply wrong. The address of a class method is something which is not related with the object of that class.
You can obtain the address of a method with the syntax:
&CLASS_NAME::METHOD_NAME;
Indeed, that statement should be something like:
tc.update = &test::update;
Additional suggestions.
Call a method by means of a method pointer.
Once you have a method pointer it is not so immediate to call the method associated with it.
As I said before, the address of the method is not related with the object of that class, so if you want to call the method you need to provide to the compiler the information about the object on which the method has to be called.
The syntax is something like:
(OBJECT.*METHOD_POINTER)(ARGS...);
Here, I propose a simple demo which shows all what I've just said.

Related

class prototypes not being read

im learing c++.I was goofing around trying new stuff and wanted to use an object class sub in class object.But i was getting error saying that the object of class sub not in not defined.I know how to solve this issue i just have to move class sub above class object so that the compiler knows that there is a class called sub.
But I feel like this will get annoying as my code grows bigger and bigger so i tried forward declaring class like we do for function prototyping.But this doesn't work as it gives me this error -
'object::thing' uses undefined class 'sub'
Here is the code -
#include <iostream>
#include <vector>
class sub;
class object;
class object
{
private:
sub thing;
int ray;
public:
void set(int n);
void get() const;
};
class sub
{
public:
int num;
public:
void set_num(int n);
void get_num() const;
};
int main()
{
object ray;
ray.set(4);
ray.get();
}
Can you guys help me out??
thanks
When a type is used in c++, at a minimum that type needs to have been declared previously.
However, in some cases, the type needs to be defined (complete) as well.
class A;
class B {
A a; // error, because A needs to be defined
};
In other cases, the type only needs to be declared (i.e. it can be incomplete):
class A;
class B {
A *a; // fine, because A only needs to be declared
};
If a type needs to be defined when it's used (as in your case), then you have no choice but to define it before hand. You could put the definition in a header file, but that file still needs to be included before the type is used.

What's the proper way of calling C++ functions from other classes?

I'm currently working on a project that has several classes, and at times, I have to call functions from other classes to make things work. I want to know if the way I'm doing it is efficient, or if there is another way I should be doing this. Here's an example
class FirstClass{ // FirstClass.cpp
public:
void aFunction(){
std::cout << "Hello!";
}
private:
}
Let's say I wanted to call aFunction in another class, I'd do this:
#include "FirstClass.cpp"
class SecondClass{ //SecondClass.cpp
public:
FirstClass getFirstClass;
// I would then use getFirstClass.aFunction();
// whenever I want to call.
private:
}
I don't feel like this is very productive. Is there a better way of doing this?
First of all why including source file FirstClass.cpp?
The proper way is to create a header file FirstClass.h and a source file FirstClass.cpp and include the header inside the source and in main.cpp.
Second: A member function is a member function it is a member of an object so you need an instance of that class to call its member. If you don't want to instantiate the class then declare the member function as a static function then you can either call it using an object or directly using class name followed by scope operator: FirstClass::aFunction().
// FirstClass.h
class FirstClass{ // FirstClass.cpp
public:
void aFunction();
}
// FirstClass.cpp
#include "FirstClass.h"
void FirstClass::aFunction(){
std::cout << "Hello!";
}
// SecondClass.h
#include "FirstClass.h"
class SecondClass{
public:
void foo();
private:
FirstClass getFirstClass;
};
// SecondClass.cpp
void SecondClass::foo()
{
getFirstClass.aFunction();
}
To make it a static:
struct A
{
static void do_it(){std::cout << "A::do_it()\n";}
};
struct B
{
void call_it(){ A::do_it();}
};
There's nothing with "productivity" to whether have a static or non-static data/function member.
The semi-colon is not redundant at the end of class body so you need t add them: class FirstClass{ }; class SecondClass{};.

C++ Pass a member function to another class

I'm trying to make a simple callback in C++ but I'm having issues doing it as I want to.
Essentially I want something like this:
class A{
void A::AddCallback(void (*callBackFunction)(string)){
/*Code goes here*/
}
}
And class B
#include "A.h"
class B{
B::B(){
A childObject;
childObject(MyCallBackFunction);
}
B::MyCallBackFunction(string arg){
/*Code goes here*/
}
}
I know that usually you would want to define the header of AddCallback with something like B::callBackFunction but I do need to import A in B so I it would be awkward to have both classes import each other. I know I've seen this before but I cant get the syntax right
Here is one option using a static member function:
#include <string>
struct A
{
void AddCallback(void (*cb)(std::string));
};
struct B
{
A a;
B() { a.AddCallback(&B::MyFun); }
static void MyFun(std::string);
};
If you want a non-static member function, then you first need to decide on which instance of B you want the member function to be invoked. For example, to invoke it on the object whose constructor registers the callback:
#include <functional>
#include <string>
struct A
{
void AddCallback(std::function<void(std::string)>);
};
struct B
{
A a;
B() { a.AddCallback(std::bind(&B::MyFun, this, std::placeholders::_1)); }
void MyFun(std::string);
};
you must call void A::AddCallback and pass callback instead of passing argument in childObject(MyCallBackFunction);

Member is inaccessible

class Example{
public:
friend void Clone::f(Example);
Example(){
x = 10;
}
private:
int x;
};
class Clone{
public:
void f(Example ex){
std::cout << ex.x;
}
};
When I write f as a normal function, the program compiles successful. However, when I write f as a class member, this error occurs.
Screenshot:
The error you're seeing is not a root-cause compilation error. It is an artifact of a different problem. You're friending to a member function of a class the compiler has no earthly clue even exists yet,much less exists with that specific member.
A friend declaration of a non-member function has the advantage where it also acts as a prototype declaration. Such is not the case for a member function. The compiler must know that (a) the class exists, and (b) the member exists.
Compiling your original code (I use clang++ v3.6), the following errors are actually reported:
main.cpp:6:17: Use of undeclared identifier 'Clone'
main.cpp:17:25: 'x' is a private member of 'Example'
The former is a direct cause of the latter. But doing this instead:
#include <iostream>
#include <string>
class Example;
class Clone
{
public:
void f(Example);
};
class Example
{
public:
friend void Clone::f(Example);
Example()
{
x = 10;
}
private:
int x;
};
void Clone::f(Example ex)
{
std::cout << ex.x;
};
int main()
{
Clone c;
Example e;
c.f(e);
}
Output
10
This does the following:
Forward declares Example
Declares Clone, but does not implement Clone::f (yet)
Declares Example, thereby making x known to the compiler.
Friends Clone::f to Example
Implements Clone::f
At each stage we provide what the compiler needs to continue on.
Best of luck.

C++ what to code if i put a class after main() function

I'm watching some video tutorials on C++ and i know you must define a function / class before it is used or called. But I like having my main() function at the top, and everything else below the main function. I know if i define a function below the main function I must declare it before it is used, but what about a class? What do I need to put above my main function to use my class below the main function.
#include <iostream>
using namespace std;
int main()
{
ClassOne one;
one.coolSaying();
return 0;
}
class ClassOne
{
public:
void coolSaying()
{
cout << "Cool stuff yo!" << endl;
}
};
I tried defining my class by placing this right before main():
class ClassOne;
but it doesn't work.
This is why header files are normally used in C++. When you're saying ClassOne one, the compiler needs to know what the class looks like to create an object of that type. It's not enough to know that the class exists somewhere (that is enough if all you want is a pointer). So the compiler needs to already have read the definition of the class.
Your class has to be defined before it is first used. Without putting it explicitly before main, the usual way is to create a header file. So you create ClassOne.h with the class declaration, and you have #include "ClassOne.h at the top of your file. In this situation the actual methods of the class would normally be in another source file, ClassOne.cpp.
A class MUST be "complete" when you create an instance of it. So there is no way you can use the class before you have defined the whole content of the class.
It is possible to do something like this:
class ClassOne;
ClassOne* make_class_one();
void use_class(ClassOne *x);
int main()
{
ClassOne* one = make_class_one();
use_class(one);
return 0;
}
class ClassOne
{
public:
void coolSaying()
{
cout << "Cool stuff yo!" << endl;
}
};
ClassOne* make_class_one()
{
return new ClassOne; // Bad idea, use uniqe_ptr, but I'm lazy.
}
void use_class(ClassOne *x)
{
x->coolSaying();
}
But in general, we don't want to do that.
One scenario where the class definition after the main() function makes sense:
#include <iostream>
using namespace std;
void f();
int main()
{
f();
return 0;
}
class ClassOne
{
public:
void coolSaying()
{
cout << "Cool stuff yo!" << endl;
}
};
void f()
{
ClassOne one;
one.coolSaying();
}
(note: all other answers are correct, but you may find this useful)
I discovered this idiom to invert the order of main and secondary function classes. I use to share small code with colleagues, everybody expects the core of the code (i.e. main) to be on top so they can edit it quickly. It works with classes and functions (without need of declaration) of course. Usually I can leave the preamble (first #includes) because those have include guards in most cases.
#include <iostream>
using namespace std;
#ifdef please_see_definitions_below_main
int main()
{
ClassOne one;
one.coolSaying();
return 0;
}
#else
class ClassOne
{
public:
void coolSaying()
{
cout << "Cool stuff yo!" << endl;
}
};
#define please_see_definitions_below_main
#include __FILE__
#endif
I use the tag please_see_definitions_below_main so it serves as comment also, but if you don't like it you can use something shorter, like AFTER.
You cannot create an actual instance of the type (variable, value member) until the type is fully defined, as its size is not known. There is no way around that, but there is a lot you can already do with a pointer to an incomplete type.