Class syntax explanation required [duplicate] - c++

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.

Related

I can't understand this type of function pointer [duplicate]

This question already has answers here:
Obtaining a function pointer to a non static member function
(2 answers)
Function pointer to member function
(8 answers)
How do pointers to member functions work?
(2 answers)
Closed 7 months ago.
I'm starting to study Unreal Engine and I saw this code:
UCLASS()
class AMyPlayerController : public APlayerController
{
GENERATED_BODY()
void SetupInputComponent()
{
Super::SetupInputComponent();
InputComponent->BindAction("Fire", IE_Pressed, this, &AMyPlayerController::HandleFireInputEvent);
InputComponent->BindAxis("Horizontal", this, &AMyPlayerController::HandleHorizontalAxisInputEvent);
InputComponent->BindAxis("Vertical", this, &AMyPlayerController::HandleVerticalAxisInputEvent);
}
void HandleFireInputEvent();
void HandleHorizontalAxisInputEvent(float Value);
void HandleVerticalAxisInputEvent(float Value);
};
I've understood everything but this line:
InputComponent->BindAction("Fire", IE_Pressed, this, &AMyPlayerController::HandleFireInputEvent);
What is the fourth parameter? I'm new to C++ but I've studied the basics of C while in college. What I can't understand is the "::". I know that the "&" means that the parameter is a pointer to the memory address of MyPlayerController, but what about the double points?
I assume that I'm passing as fourth parameter the HandleFireInputEvent function of the MyPlayerController class but I would like to know more about you.
Many thanks.
The fourth argument is the address of a class member function. And that function has a name within the class scope, just as when you have to implement a class member.

Problem using pointers to member functions in C++. Compiler says "Reference to non static member function must be called" [duplicate]

This question already has answers here:
C++ Call Pointer To Member Function
(4 answers)
Calling C++ member functions via a function pointer
(10 answers)
Closed 9 months ago.
Consider this class:
class Downloader {
private:
bool video_or_audio;
// other variables [...]
// [...]
void downloadVideo(std::string videoURL);
void downloadAudio(std::string audioURL);
public:
void download();
}
Now, download() is defined this way:
void Downloader::download(){
std::ifstream url_list;
void (*download_func)(std::string) = video_or_audio == 0 ? downloadVideo : downloadAudio; // Compiler says here: "Reference to non static member function must be called".
if(video_or_audio == 0){
url_list.open("video_list.txt");
}
else{
url_list.open("audio_list.txt");
}
std::string url;
while(std::getline(url_list, url)){
download_func(url); // Calling the function pointed by the pointer defined in line 2 of the function download().
}
}
My compiler (clang) says: "Reference to non static member function must be called" in the second line of function download() definition. Why is this happening and how can I solve this problem?
A solution appears to be defining downloadVideo() and downloadAudio() functions to be static in the class declaration. However, if I do so, I cannot access private variables members of class Downloader, that's not desirable, as I need these variables.
Thank you!
Once calling a member function by pointer, you need to provide two things:
Member function itself
Address of particular instance of given class at which the member function to be called (because the function can access class members thus you have to advise which of the instances is the right one)
void (Downloader::*download_func)(std::string) = video_or_audio == 0 ? &Downloader::downloadVideo : &Downloader::downloadAudio; // Correct the signatures.
...
while(std::getline(url_list, url)){
(this->*download_func)(url);
}
So, here we changed download_func from "just function pointer" to a member function pointer. Then, later in the loop body, we call this member function on this instance (however you can pass an instance as a param if necessary).

Assignment of function pointers (effective c++ item 35) [duplicate]

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.

Keyword const in class declarations [duplicate]

This question already has answers here:
Meaning of 'const' last in a function declaration of a class?
(12 answers)
Closed 7 years ago.
I understand that the keyword const marks variables, parameters etc as read only. In a class declaration why is const used at the end of a member declaration, for example:
QString getClassName() const;
Declaring a method const means that the method won't change the state of the object and thus it can be called on const instances of the class.
Notice that const-ness is enforced by the compiler. const methods can't modify member variables unless they are declared mutable. It's very common to have mutable locks so that const methods can still be synchronized.
It basically means that the function is "promising" that it won't change the calling object.

Pass a reference to a constructor [duplicate]

This question already has answers here:
Reference as class member initialization
(4 answers)
Closed 9 years ago.
I am sorry if this meight be a really simple question but i am new to c++ and working on a simple vocable trainer for understanding c++. (come from java..)
I'd like to pass a const FileManager as reference to my Logic. But i don't get it work. I don't want to have a copy or such.
So i tried it like this: (the main)
FileManager& file = FileManager();
Logic logic = Logic(file);
Inside of the Logic i'd like to store the reference:
class Logic
{
public:
Logic(const FileManager& manager);
~Logic();
private:
const FileManager& m_fileManager;
};
Logic::Logic(const FileManager& manager) :
{
m_fileManager = manager;
}
Thanks
Once the body of a constructor is entered, all member variables have already been initialized. Thereafter, you can only assign to them. This can't work with references - as we know, they need to be initialized when their lifetime begins.
You need to use member initializer list:
Logic::Logic(const FileManager& manager)
: m_fileManager(manager) // m_fileManager is initialized here
{
}
Consider if you really want a reference member. For one, they make your class non-assignable. A smart pointer might be a better choice.
Your example has three flaws. The first, is that you try to initialize a none const reference with a temporary object:
FileManager& file = FileManager();
Most likely you just want to use a FileManager instance here:
FileManager file;
Second, references must be initialized. You achieve this by using the initializer list syntax:
Logic::Logic(const FileManager& manager)
: m_fileManager( manager )
{
}
In addition, the initializing, you use for Logic requires that Logic is assignable. Simply use:
Logic logic(file);
If you have reference members in a class, objects of that class are not assignable by default.