I do not know how to call a function with a reference in it :( It is a silly noob question I know.
The header is let's call it ref.h has a function in it that is:
virtual int funcName (Bike &biker, BikeArray &bikearray, int x, int y .... )
Within ref.h there is another header that is called Bike.h.
How do I call funcName from my main.cpp (obv. I included Bike.h and ref.h
I have called other functions from ref.h in my program, but the other functions did not have references to Bike in them, just variables... How do I declare everything?
What I have so far:
ref *ref;
Bike bike;
BikeArray bikearray;
int x, y;
ref = ref::createinstace(configFile);
ref->funcName(bike, bikearray, x,y);
ref->funcName should return results based on the configFile i passed. I have done this earlier with another function in ref.h, but that function only had int's and doubles... no objects to Bike ...
... and I get the Error "no matching function for call ref::funcName(Bike&, BikeArray&, int&, int&)
Sorry, I know this is a novice question!
You pass objects per reference as you would pass them per copy:
someObj.funcName(myBiker, myBikeArray, 42, ...);
Note that, if a function takes arguments per non-const reference, this indicates that the function might change them. (See here for more on that.)
Also, you cannot pass rvalues (temporary objects) as non-const arguments. That means that, if you have a function that returns a biker:
Biker getBikerByNumber(int num);
you can't use it as an argument to funcName:
someObj.funcName(getBikerByNumber(42), myBikeArray, 42, ...); // won't compile
because rvalues to not bind to non-const references. They do bind to const references, though (and also to the rvalue references to be introduced by the next C++ standard and already implemented by some compilers).
You call the function the same way regardless of whether its arguments are passed by value or by reference.
Bike foo;
BikeArray bar;
funcName(foo, bar);
Pass it values not pointers.
Bike biker;
funcName(biker, ...);
funcName is virtual so must be a class member function. You therefore need to have a reference or pointer to the class that it is a member of first.
It would have been enough for Bike to be forwardly declared but presumably Bike.h contains the class definition for Bike. BikeArray might be a class or a typedef, for example
typedef std::vector<Bike> BikeArray;
To call funcName you would then call it using . or -> on the class reference or pointer you have, then use an instance of Bike and an instance of BikeArray to be written into, plus whatever other parameters it requires.
Related
I am new to c++ and im trying to write a simple c++ wrappers to integrate with this third party c++ library; which comes with bad documentation.
function to integrate with (this is all the documentation that came with this function):
virtual ImageCoord Raster::groundToImage(const XyzCoord & groundPt,
double desiredPrecision=0.001,
double* achievedPrecision=null) const
Text about function: This method converts the given groundPt (x,y,z in meters) to a returned image coordinate (line, sample in full image space pixels).
there is also some class documentation
Raster Class Ref
inherits from GeoModel
Public member functions:
virtual ImageCoord groundToImage (const XyzCoord &groundPt, double desiredPrecision=0.001, double *achievedPrecision=NULL) const =0
in my code i have:
//this is implemented correctly
const XyzCoord xyz(284971.17549099098, -126866.36533847413, 6350003.627515804)
double desiredPrecision = 0.000001;
double achievedPrecision = 0.0;
// not sure if this is what the documentation meant by "image coordinate" but it comes with the library
// ImageCoord(double line, double point)
ImageCoord imagePoints;
// the part im confused about, what is the proper way to invoke the above function, the below line was me trying out how to call the method
const Raster::groundToImage(&xyz, imagePoints);
Sorry for my ignorance in c++ but I've been baffled. I have lot of programing experience (8 plus years, just none with c++ so i understand programing terms, concepts and design patterns).
Im also trying to understand in the function defination what does this mean
const XyzCoord & groundPt
I was able to compile with
XyzCoord xyz(204971.17549099098, -106866.36533847413, 6350003.627515804);
Raster* service;
ImageCoord imagePoints = service->groundToImage(xyz); //segmentation error occurs on this line
but i then get a runtime error "Segmentation fault"
This is a non-static member function of a class named Raster.
You are supposed to invoke it via member access obj.groundToImage(/*args*/) where obj is an object of the class type to which the function belongs or a class type derived from that class.
Or, if the call happens inside another non-static member function of the same class or a derived class, it could just be groundToImage(/*args*/) which will call the function implicitly on the current object.
With virtual it may also be possible to invoke the function on an object of a base class of Raster, depending on where the virtual function has been declared first in the class hierarchy.
There are certain more specialized situations where a qualified call replacing groundToImage with Raster::groundToImage in either of the above could also be the intended behavior.
The const qualification of the function is irrelevant. It just means that the function can be called whether obj is const-qualified or not. Similarly the const-qualification on the function parameter is irrelevant. It just means that you can pass either a const- or non-const-qualified first argument. You don't have to make xyz const to be able to pass it. Only the other way around, passing a const-qualified expression to a non-const reference parameter is a problem. const is intended to signal that the function will not modify the argument and therefore doesn't care whether or not it is const-qualified.
const only makes sense when used in a declaration or type. Something like
const Raster::groundToImage(&ecef, imagePoints)
as a supposed function call doesn't make syntactical sense.
The function also expects up to three arguments of the specified types and returns a ImageCoord. You are not supposed to pass one as an argument. It is what the function returns.
The arguments should probably be xyz, desiredPrecision and &achievedPrecision given that you already declared them with the correct types.
It probably wants the last one as pointer because it is an out-parameter.
What the object on which the member function is called on is supposed to be is unclear from what you have shown. We don't know what ecef is though...
TL;DR:
ImageCoord imagePoint = someRasterObject.groundToImage(
xyz,
desiredPrecision,
&achivedPrecision
);
Or
ImageCoord imagePoint = somePointerToRasterObject->groundToImage(
xyz,
desiredPrecision,
&achivedPrecision
);
From the signature given:
virtual // A derived class's implementation of
// this function can be called via a
// pointer or reference to a parent
// class object
ImageCoord // This function returns an ImageCoord
// object
Raster:: // This is a member of the Raster class
groundToImage( // This function is named groundToImage
const XyzCoord & groundPt, // The first argument to this function is a
// reference to a constant XyzCoord
// object
double desiredPrecision=0.001, // The second argument is a double with a
// default value of 0.001 if not provided
double* achievedPrecision=null // The third argument is a pointer to a
// double with a default value of null if
// not provided
)
const // This function can be called on a
// constant Raster object
That means you need 2-4 things to call this function:
A (possibly const-qualified) Raster object to call the function on
An XyzCoord object to pass as the first parameter
(Optional) A double to pass as the second parameter
(Optional) A pointer to a double to pass as the third parameter
While nothing in your question explicitly states it, I would assume the function uses the 3rd parameter as an output. I would assume it writes the actually achieved precision to the double pointed to by the pointer you pass it, so you'll probably want to just pass it the address of a local double variable.
Each non-static method in a class is called on behalf of some object of that class (or some derived class), and the object is accessible within a method by an implicitly defined this pointer.
The const qualifier appended after the parameters' list of the method applies to that this value. In other words, it declares this of a type classname const* instead of classname*.
As a result the compiler will reject any attempts to modify the *this object from within the const-qualified method, so the method can be safely used on non-modifiable objects.
For example, the length() method of the std::string class is declared as
size_t length() const;
so when you use it like, say:
std:string s;
....
size_t len = s.length();
you can be sure the s variable will not be modified during calculation of len value.
I'm trying to implement more flexibility in my numerics by allowing me to choose different forms of a mathematical function and vary their parameters through instantiating them as objects of a certain class. That class includes certain mathematical functions I may choose plus parameters that I can vary. The constructor of the class sets a member function pointer in the class to a member function according to what mathematical function I want. I want to solely use the pointer to call whatever function it points to by directly using the pointer in my routine.
However, that proved daunting as I didn't know that member function pointers require a certain syntax and seem to work somewhat differently from regular function pointers according to what I could gather. I've experimented quite a bit and constructed myself a minimal example shared below.
#include<iostream>
#include<string.h>
#include<cstdlib>
#include<stdio.h>
class Someclass
{
public:
// constructor to set pointer
Someclass(std::string);
// member function pointer to hold functions
void (Someclass::*fptr)();
// auxiliary function to call testfunction via pointer
void call ();
// testfunction
void foo();
};
// testfunction
void Someclass::foo()
{
printf("foo says hi! \n");
}
// call via specific function
void Someclass::call()
{
(this->*fptr)();
}
// constructor
Someclass::Someclass(std::string name)
{
if(name=="foo")
{
this->fptr = &Someclass::foo;
}
}
int main()
{
Someclass someobject("foo");
someobject.foo(); // direct testfunction call: Works OK
someobject.call(); // call via auxiliary function: Works OK
//(someobject.*fptr)(); // direct pointer dereferencing: Gives Error
return(EXIT_SUCCESS);
}
It shows that I can access the pointer by use of another member function that just calls whatever the pointer points to via use of a this pointer. However, I still can't seem to get the function call to work if I try to use the pointer directly in my main function through the line,
(someobject.*fptr)()
This particular expression leads to my compiler complaining about the scope and if I include the class scope, the compiler mentions invalid use of non-static members. Still, I'm confused as to why my implementation here doesn't work and if it does, how the proper syntax in my problem would be and why that has to be so.
Any insights would be really appreciated.
fptr is a member of the object, not a variable local to main. In such respect member function pointers behave exactly the same as all other variable types. You were so close, and just need to qualify the function pointer name with the object name:
(someobject.*(someobject.fptr))();
The reasons for this is .* indicates a pointer to member function and does not directly reference the members of an object like the . and .-> operators. Since fptr is a member of Someclass and not a local variable you need to reference it directly like so
(someobject.*someobject.fptr)();
I can't see what's wrong with my code. I have a an std::vector which is a private member of my class Foo. It is not declared as const, even when the error the compiler gives suggests so.
(At Foo.h)
private:
std::vector<std::string> tableBackup;
I'm calling a function (from Foo.cpp):
BackupTable(this->tableBackup);
This method is into DatabaseLoad.cpp and .h:
public:
void BackupTable(std::vector<std::string> &tableBackup);
Defined as:
void DatabaseLoad::BackupTable(std::vector<std::string> &tableBackup){
//whatever...
}
I'm getting the following error when I call the method from Foo.cpp:
No matching function for call to 'DatabaseLoad::BackupTable(const std::vector<std::basic_string<char> > &)'
What's the problem? Currently using C++11, but I guess this has nothing to do with that.
You are calling the BackupTable function in a context where the DatabaseLoad object is const-qualified, therefore the compiler is expecting a call to a const-reference.
If you are not planning on modifying the vector, you should declare the function as:
void BackupTable(const std::vector<std::string>& tableBackup);
I can guess that you are calling BackupTable from const method of Foo class
You seem to be calling BackupTable(this->tableBackup); inside a member function which is qualified as const. This means that this is of type const Whatever*, and thus all data members are implicitly const-qualified inside this member function as well. So they cannot be bound to a non-const reference.
You have two sane options:
If BackupTable does not modify its argument, it should accept it as const & instead of just &.
If it does modify its argument, it means the calling function modifies its this object, so it should not be marked as const.
A third (far less likely) option is that tableBackup is actually an implementation details of your class and the fact that it changes does not affect the "logical constness" of the class. If that is so, you can mark it as mutable (that way, even const functions will be able to modify it). At the same time, you must introduce some form of synchronisation mechanism (e.g. a mutex) whenever you access the mutable tableBackup (or any mutable member). The reason is that all of the standard library expects const operations to be thread-safe. An emerging idiom for this is adding a private member like this:
mutable std::mutex mutables;
And locking mutables whenever you access (even just for reading!) a mutable member.
I think that 'this' is const in ' BackupTable(this->tableBackup);'. You call the ' BackupTable' in a 'Foo() const' function.
AFAIK, in C++, invoking another member function within a member of function of the same class should not require the "this" prefix as it is implicit. However, in the specific case of using function pointers, the compiler requires it. The following code compiles correctly only if I include the "this" prefix for the call via func pointer -
When function pointers are used can the compiler deduce when it points a member func of the same class?
class FooBar
{
private:
int foo;
public:
FooBar()
{
foo = 100;
}
int GetDiff(int bar)
{
return abs(foo - bar);
}
typedef int(FooBar::*MyFuncPtr)(int);
void FooBar::Bar()
{
MyFuncPtr f = &FooBar::GetDiff;
(this->*f)(10);
GetDiff(10);
}
};
It's required, because member function pointers (which are not the same thing as function pointers) are not bound, and you can use them with different objects.
(this->*f)(10);
(foo.*f)(10);
// etc.
When you invoke an instances member function the this pointer is implicitely put to the function parameters. Thus you need to specify this also when invoking that function via a function pointer.
f isn't a member of the class, but a local variable, you could also specify another instance pointer instead of this, so the compiler can't deduce that. Same for member function pointers as class member variables.
The simple question is that it is a matter of language design and the language was designed this way.
Inside a member function, and to ease the common syntax when the compiler encounters an identifier it performs lookup starting from this class (plus ADL on the arguments), and if the lookup finds an unambiguous non-static member of this type (or of a base type) then the compiler will inject this-> for you (that is, applies operator-> to the this pointer).
In the case of a pointer to member the process is quite different. The pointer (which is not really a pointer, but for the sake of argument) is found by lookup, but it is your responsibility to provide the object on which it will be called and use the appropriate operator (either .* for calling a pointer to member on a reference, or ->* for calling the member on a pointer).
Note that the operators that are called are different, and that the process is different altogether (in one case lookup finds a member, in the other it finds a variable that happens to be pointer-to-member), but the most important part is that calling pointers to members is infrequent enough, and calling them on this is even less frequent that it does not not to warrant an exemption on the syntax for a small use case.
f isn't a member of FooBar. So if you want to call f on an instance of FooBar, you have to tell it which instance.
In your example, f does contain a member of FooBar, but the compiler doesn't know that.
This happens because of the way the C++ runtime handles classes while you are not looking.
Basically it would be inefficient to store the function pointers in the instance, so the compiler builds a class specific table with function pointers that have the same arity as the member functions you defined and that get the this pointer passed at runtime (AFAIK visualc passes the pointer via ecx, I'm not entirely sure what happens on GCC)
So basically when you do
instance->foo(10);
You are telling the runtime to call function foo with the parameter 10 and pass (instance) as the this pointer, wich is why you have to specifically say which object it has to be called on.
I am trying to store pointers to memberfunctions of different Classes in C++. What are the possibilities in C++?
I would like to do this:
class A {
T0 f(T1,T2);
};
class B {
T0 g(T1,T2);
T0 h(T1,T2); //interfaces cant be used since the number of functions per class differs.
};
typedef WHATTOPUTHERE type;
type x;
x = A::f;
x = B::h;
Update: Another Problem is that the code should be continueable like this:
B myB;
myB::x(a,b); //not sure about the syntax, should result in myB::h(a,b) being called
This means that I can not bind at the time I store the pointer, since the instance does not exist (yet).
Function objects to encapsulate your function pointers should work.
boost::function is one option, maybe something like this:
class SomeObj
{
public:
void SetInt(int i);
};
SomeObj myObject;
std::vector<boost::function> memberFuncs;
// in the template arg to boost::bind specify the function type
// _1 here denotes late binding so you can pass whatever value you want when invoked
// you could simply bind a parameter as a variable or literal instead
memberFuncs.push_back(boost::bind<void(int)>(&SomeObj::SetInt, &myObject, _1));
memberFuncs[0](42); // myObject->SetInt(42);
Untested/uncompiled code disclaimer this is just for a general idea.
One possible implementation (using C++11) can easily be done using std::function and a lambda like this:
typedef std::function<void(int)> FunctionType;
SomeClass someClass;
FunctionType func = [&someClass](int argument)
{
someClass.SomeMemberFunction(argument);
};
To have a pointer to Fred::f(char, float) you need this sort of pointer:
int (Fred::*)(char,float)
http://www.parashift.com/c++-faq-lite/pointers-to-members.html
The answer to your particular question is that there is no type that you can add to the typedef and make the code compile. The reason is that member function pointers take a hidden argument of the type of the class form which they are obtained. The type of that hidden argument will be different when you take the address of a member function from A or B.
The next question is whether it makes sense or not from a design perspective, considering that you cannot apply the function pointer A::f to an instance of type B, what is the point of considering member pointers of A and B together?
Now, there are possible workarounds for this particular problem (if it makes sense in your case, but I would first review the design) that involve performing type-erasure on the function pointer to remove the hidden argument and generate an object that is callable with the given set of arguments and return type that is common to all of the member functions. This is already done inside std::function (alternatively boost::function if your compiler does not support C++11), as has been suggested before:
A a_instance;
std::function< T0 (T1,T2) > f( std::bind( &A::f, &a_instance, _1, _2 ) );
T0 r = f( T1(), T2() );
Note that part of the trick is that std::bind binds the member function pointer with the pointer to the instance, filling in the hidden argument, while leaving the other two arguments unbound. At this point, because the result of bind does no longer depend on the type of the first argument, type-erasure can be applied removing A from the type of the resulting object.