Class member function cannot call another member function of same class? - c++

I'm writing a private member function for a class (function1) and for a chunk of the code I decided it'd be easier to put that chunk into it's own function (function2) , and call it from function1. However, the compiler is saying that function2 needs an object. This doesn't make sense to me, because an object has to be created in order for function1 to work, so the object for function2 seems like it should just be "this".
int ClassName::function1(args)
{
//some code;
//some code;
function2(args); //says I need an object to call the function here
//some code;
}
int ClassName::function2(args)
{
//some code;
}
The exact error code is "A nonstatic member reference must be relative to a specific object". I've been searching for hours and every instance of this comes from someone calling a class member function from outside of the class without using a object pointer. I cannot find anything for a class member function calling another class member function. I also thought I had called member functions from other member functions in the past without trouble, so I'm super confused. I could just delete function2 and do all calculations inside function2, but then I wouldn't learn anything!
I tried switching the order of the function definitions in the cpp file. The order of the prototypes in the header. Changed function2 from private to public. No dice. I've exhausted google, my own programming knowledge, and any experimentation that I could think of, so I have to ask you guys for help now. If you need extra info, let me know, although it seems like the exact code inside my functions would be irrelevant as far as the problem goes.

Related

Calling game functions with string variables

I am trying to call this function in a c++ dll:
public static void AskTrade(string traderPartnerId)
What I do to call this is:
auto Trade = reinterpret_cast<void(*)(std::string)>(BaseAddress + 0xDE54B0);
Trade(D39DSAR2);
It is inside of a special void that makes the calling work. Because when I call functions without any variables or functions with int as variables, it does work.
But when I try to call this, nothing happens. The game is c# and I code in c++, that must be the reason I guess. I don't know how to fix it though.
I would very much appreciate it if any of you would know and tell me a solution.

Use function-pointer as proxy to member-function

Assume a class like this:
class Speaker {
public:
void (*saySomething)();
}
The point is that we can instantiate that class and call the stored function pointer in order to make it say something (whatever that turns out to be). The background to such an approach is to have the actual function reside in a shared library and Speaker acts as some sort of wrapper class (The function gets resolved in the library and the pointer is assigned to the variable in the class).
Now consider we have another class that extends Speaker:
class ConstantSpeaker : public Speaker {
protected:
std::string message;
void doSpeak();
}
with the method's implementation like this:
ConstantSpeaker::doSpeak() {
std::cout << message << std:endl;
}
Now I want to assign the saySomething pointer in a way so that the call is somehow re-routed to ConstantSpeaker::doSpeak(). This however isn't possible directly as doSpeak() is a member function and saySomething is a pointer to a non-member-function.
Another idea I had was to create doSpeak() as a friend-function of ConstantSpeaker instead. Then the pointer-assignment works fine but now doSpeak() would require the object holding the actual message as an argument in order to be able to access the message.
To me it seems as if there should be a (more or less) straight-forward way of doing this given that I can only ever call Speaker::saySomething when having an instance of a Speaker at hand. Therefore the availability of the corresponding object shouldn't be a problem but still I can't figure out how I have to assign that pointer.
The only solution I could come up with is to add a public virtual Speaker::doSaySomething function whose implementation will call the function pointer (which is then no longer public in order to prevent miss-usage) and that can be overwritten by ConstantSpeaker to call ConstantSpeaker::doSpeak() instead.
Is there another solution to this problem?
Another solution is just to use a standard std::function<void()>, and then it can be still declared as public.
Also, instead of bare function pointer, you can use pointer to member function, but be aware about slicing, when using it inside a base class.
But, I think, the most trivial way of doing this is just by using virtual function, like you've mentioned.
Maybe tell more about your context? What is the problem you are going to solve?

C++ function prototype outside class

In c++ how is this a proper function prototype?
class Car{
//some member variables and functions
};
Car someFunctionName();
I understand that when making member functions and variables you would prototype the function in the class and then later the definition would be something like this
double Car::someOtherFunctionName() {}
My professor keeps putting the first example of a prototype in example code and I can't seem to grasp the concept. TIA
Not all functions in C++ are member functions. The function your professor has prototyped is a standalone function which returns a Car.
To quote UKMonkey:
People like to say that C++ is Object Oriented. It's not. It's Object Capable. You CAN use objects, if you want.

Is there any way to change the scope of a callback without changing the paramaters?

I am using SDL2_mixer library, but I believe that the question should hold for the general case also.
Currently, a function that I would like to use, Mix_HookMusicFinished(void (*music_finished)(void)) has a set callback to the global scope for a C style function. However, I would like to have that callback be set to a member function within my own class void CMusic::musicFinished() without having the need for a function in global scope.
Is there anyway to do this? Something like Mix_HookMusicFinished(musicFinished) would be great, but that directly has an error of argument of type "void (CMusic::*)()" is incompatible with parameter of type "void (*)()"
You need to make a "wrapper" function. However, the problem here is that you also need to be able to find the CMusic object that you want to "finish" - this is really what the crux of
argument of type ... is incompatible with ...
is all about. Since there is no way to pass a parameter to the musicFinished object, you will need some other way of "finding" the CMusic object.
If we assume there is a way to do that, then something like this would work:
class CMusic
{
...
public:
...
static void musicFinishedWrapper();
void musicFinished();
...
};
void CMusic::musicFinishedWrapper()
{
CMusic* music = getTheMusicSomehow(); // No idea how you do this - depends on your code.
music->musicFinished();
}
The reason you have to have a CMusic object is that your musicFinished expects a (hidden) this pointer argument - which is the value in music in my little function.
You could move musicFinished to your CMusic class and declare it as a static class method. static class methods aren't called on an object; they therefore don't have an implicit argument to specify the value of the this pointer, and they therefore can have the same signature as freestanding functions. You additionally can make it private to prevent anything but CMusic from using it.
However, since your musicFinished method currently works as a freestanding function and therefore probably doesn't need access to CMusic's protected or private members, and since your efforts to limit its scope presumably means that you don't want other things to call it, I personally would leave your musicFinished function as freestanding but declare it as static (or move it to an anonymous namespace, if you prefer) within the CMusic source (.cpp or .cc) file. Doing so would restrict its scope to the source file (the "compilation unit"). An advantage over a private, static class method is that it does not need to be exposed at all in a header file, so it is in some sense more private.

Which is best for a repeating piece of code?

I have a class with two member functions that share a piece of code:
void A::First()
{
firstFunctionEpilogue();
sharedPart();
}
void A::Second()
{
secondFunctionEpilogue();
sharedPart();
}
Currently firstFunctionEpilogue(), secondFunctionEpilogue() and sharedPart() are not function calls but just pieces of code, sharedPart() code being duplicated. I want to get rid of the duplication.
The shared piece of code doesn't need access to any members of the class. So I can implement it as any of the three:
a static member function,
a const non-static member function or
a local function.
Which variant is better and why?
If your function accesses state but does not change it then use a const member function.
Your case:
If it your function 1) doesn't need access to any member of the code, and 2) is related to that class, then make it a static function of your class.
That way it is clear that it is not modifying state, nor based on the state of the object.
An extra case you didn't mention:
There is another thing you can do too. And that is to make your SharedPart take in a member function pointer and to call it and then process it's main body. If you have a lot of First(), Second(), Third(), Fourth(), ... such functions then this can lead to less code duplication. That way you don't need to keep calling SharedPart(); at the end of each member function, and you can re-use First(), Second(), THird(), ... without calling the SharedPart() of the code.
I'd say:
It probably doesn't matter, so it's not so much "best practice" as "just don't do anything crazy".
If the class and all its members are defined in its header, then a private static member function is probably best, since it clearly indicates "not for clients". But there are ways to do this for a non-member function: don't document it, put in a comment "not for clients", and stick the whole thing in namespace beware_of_the_leopard.
If the class member functions are defined in a .cpp file, then little helper functions like this are best as free functions in the .cpp file. Either static, or in an anonymous namespace.
Or it could be in a different class.
Or, if it's a member, it could be virtual.
There are a lot of decisions, and I wouldn't stress out about it too much. Generally, I opt for a const non-static member function as a default unless I have a good reason not to do it that way.
Prefer static if clients need to call it without having an instance
Prefer local functions if you don't want to clutter the .h file or you want it completely hidden in the .c
Make it a non-member function
The shared piece of code doesn't need access to any members of the class.
As a general rule, if a piece of code doesn't need access to any members of the class don't make it a member function! Try to encapsulate your classes as much as possible.
I'd suggest doing a non-member function in a separate namespace that would call the public methods and then call the function you made for the shared code.
Here is an example of what I mean :
namepsace Astuff{
class A{...};
void sharedPart(){...};
void first(const A& a);
void second(const A& a);
}
void Astuff::first(const A& a){
a.first();
sharedPart();
}
a static member function, a const
non-static member function or a local
function.
Generally, it should be a member function of another class, or at least non-static member of the class itself.
If this function is only called from instance members of a class - probably its logical meaning requires an instance, even if syntax does not. Can anything except this object provide meaningful parameters or make use of the result?
Unless it makes sense to call this function from outside of the object instance, it shouldn't be static. Unless it makes sense to call this function without accessing your class at all, it shouldn't be local.
Borrowing examples from Brian's comment:
if this function changes global state, it should be member of a class of global state;
if this function writes to file, it should be member of a class of file format;
if it's refreshing screen, it should be member of... etc
Even if it's a plain arithmetic expression, it may be useful to make it a member (static or not) of some ArithmeticsForSpecificPurpose class.
Make it a non-member non-friend function. Scott Meyer's has a great explanation for this here (and also Item 23 of Effective C++ 3rd Edition).
As a rule of thumb "try to keep it as local as possible but as visible as necessary".
If all code calling the function resides in the same implementation file, this means keeping it local to the implementation file.
If you'd make it a private static method of your class, it would not be callable by implementaions including your class, but it would still be visible to them. So every time you change the semantics of that method, all implementaions including your calls will have to recompile - which is quite a burden, since from their point of view, they don't even need to know those sementics.
Thus, in order to minimize unnecessary dependencies, you would want to make it a static global function.
However, if you should ever find yourself repeating this global function in mulitple implementation files, it would be time to move the function into a seperate header/implementaion file pair, so that all callers can include it.
Whether you place that function into a namespace, at global scope, or as a static function in a class is really up to taste.
On a final note, if you go for the global static function, there's a "more c++ like" version: anonymous namespaces. It has the nice property that it can actually store state and also prevents users for being able to even forward declare any of its functions.
// in your .cpp file
namespace /*anonymous*/
{
void foo()
{
// your code here
}
};
void MyClass::FooUser1() { foo(); }
void MyClass::FooUser2() { foo(); }