This question already has answers here:
function pointer assignment and call in c++?
(2 answers)
Closed 4 years ago.
In effective c++, item 35, the author introduces the strategy pattern via function pointers. Specifically on page 172
class GameCharacter;
int defaultHealthCalc(const GameCharacter& gc);
class GameCharacter {
public:
typedef int (*HealthCalcFunc)(const GameCharacter&);
explicit GameCharacter(HealthCalcFunc hcf = defaultHealthCalc)//why not &defaultHealthCalc?
: healthFunc(hcf)
{}
int healthValue() const
{ return healthFunc(*this); }
...
private:
HealthCalcFunc healthFunc;
};
On the sixth line, why the assignment to the function pointer HealthCalcFunc is defaultHealthCalc instead of &defaultHealthCalc ?
Since the compiler knows that you are assigning a value to a pointer-to-function, it is enough to specify the name of the function you want -- the syntax is unambiguous.
If you wanted to add the ampersand to make it clear, the syntax allows that, but it isn't necessary.
Similarly, when calling a function from a pointer, you can either use the name of the pointer directly (as is done in the example code), or explicitly dereference it using the '*' operator. The compiler knows what you mean in either case.
Related
This question already has answers here:
How can I pass a member function where a free function is expected?
(9 answers)
how to pass a non static-member function as a callback?
(8 answers)
Pass Member Function as Parameter to other Member Function (C++ 11 <function>) [duplicate]
(2 answers)
Closed 4 months ago.
I need to change the prototype of a function pointer of a class. So, I was hoping inheriting it and doing the following would work, but it doesn't ("invalid use of non-static member function 'void B::myIntCallback(unsigned int)"):
class A {
public:
typedef void (*intCallback_t)(unsigned int myInt);
A(intCallback_t intCallback) {}
};
class B : A {
public:
typedef void (*charCallback_t)(unsigned char myChar);
B(charCallback_t charCallback) : A(this->myIntCallback) {
charCallback_ = charCallback;
}
private:
charCallback_t charCallback_;
void myIntCallback(unsigned int myInt) {
charCallback_((unsigned char)myInt);
}
};
Does anybody know how I can solve this? I can't change class A.
You are trying to pass a member function (B::myIntCallback) to a function pointer argument. Since the member function needs an object to be called on, his would require some kind of capturing, e.g. a lambda capturing this or an std::bind expression. Unfortunately, neither is possible with a plain function pointer, see also Passing capturing lambda as function pointer.
If possible, you may want to consider changing the class A to accept either a std::function or a template argument as the type of the callback. See also Should I use std::function or a function pointer in C++?.
This question already has an answer here:
Factory Pattern: typedef Class *(createClassFunction)(void)
(1 answer)
Closed 8 years ago.
I've come across a declaration inside a C++ Struct{..} that I've never seen before.
Can anyone tell me what it means;
struct DerivedMesh {
char cd_flag;
void (*calcNormals)(DerivedMesh *dm); // <-- What is this?
It kind of looks like it's dereferencing a pointer called calcNormals, but that's all I can make out.
This is a C syntax for declaring function pointers.
In this particular example, DerivedMesh will have a member calcNormals that is a pointer to a function accepting single argument of type DerivedMesh*. It can be called like an ordinary function:
void foo(DerivedMesh* dm) { ... }
DerivedMesh dm;;
// Init members and set calcNormals to actual function
dm.cf_flag = whatever;
dm.calcNormals = foo;
dm.calcNormals(&dm); // calls foo
This
void (*calcNormals)(DerivedMesh *dm);
is class data member definition with name calcNormals that has type of pointer to function of type void( DerivedMesh * )
This question already has answers here:
Meaning of 'const' last in a function declaration of a class?
(12 answers)
What is meant with "const" at end of function declaration? [duplicate]
(6 answers)
Closed 8 years ago.
why is the purpose of "const" in that case?
std::string List::reqClubName() const
{
return m_Club;
}
Thanks
Banning the modification of members is not the only reason to qualify a member function as const. Whether you want to modify members or not, you can only call a member function on an object through a const context if the member function is marked const:
#include <iostream>
#include <string>
struct List
{
std::string reqClubName()
{
return m_Club;
}
private:
std::string m_Club;
};
int main()
{
const List l;
std::cout << l.reqClubName();
// ^ illegal: `l` is `const` but, `List::reqClubName` is not
}
Neither the language nor the compiler care that reqClubName doesn't try to modify the object anyway; your program will not compile.
Because of this, a const suffix should be your default approach unless you do need to modify a data member.
The const after a member function says that the function does not modify member data in the class it is a part of.
This question already has answers here:
Meaning of 'const' last in a function declaration of a class?
(12 answers)
Closed 9 years ago.
I am learning C++ in Qt environment and I was going through one of the sample code online.
Can anyone please explain this syntax to me?
const TicTacToe * GetTicTacToe() const { return m_tictactoe.get(); }
Why is there a const before the opening bracket of a function? Is it a pointer or multiplication?
the full class is as follows, but the syntax of the instructions mentioned above is not clear to me
class QtTicTacToeWidget : public QWidget
{
Q_OBJECT
public:
explicit QtTicTacToeWidget(QWidget *parent = 0);
const TicTacToe * GetTicTacToe() const { return m_tictactoe.get(); }
void Restart();
The first const is to signify that the variable pointer TicTacToe can't be changed. The second constant after the function declaration says that anything that happens inside this function will not change any member variable inside the class. Because it effectively does not change memory data on the class, it can be used when you use any constant object of that class. For example:
const QtTicTacToeWidget myConstObject;
// Since myConstObject is a constant, I am not allowed to change anything inside
// the class or call any functions that may change its data. A constant function
// is a function that does not change its own data which means I can do this:
myConstObject.GetTicTacToe();
// But I can not do the next statement because the function is not constant
// and therefore may potentially change its own data:
myConstObject.Restart();
The const between before the opening bracket signifies that the function is a const member function. It essentially says that it guarantees to not modify the class and therefore can be called on an object declared as const.
Well that, and it also allows the function to modify mutable variables in a const class.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why should I prefer to use member initialization list?
Class A has a member variable i. i can be initialized or assigned during object creation.
A) Initialise
class A {
int i;
public:
A(int _i) : i(_i){}
}
B) assign
class A {
int i;
public:
A(int _i) : { i = _i}
}
My question is what is the basic difference between these 2 approach?
The difference lies in which C++ mechanism is used to initialize i in your class. Case (A) initializes it via constructor, and case (B) uses the assignment operator (or a copy constructor if no assignment operator is defined).
Most C++ compilers would generate exactly the same code for this particular example, because you're using int, which is a "plain old data" type. If i were a class type, it could make a great deal of difference.