[Tutorial] C++ Callbacks
I'll be explaining how to create and use callbacks.
First, I'll start by explaining what a callback is. A callback is basically a pointer to a function that executes when a certain event
happens. This could be a button click, a window resize, or anything else. For this example, I'll be creating a button class that has an OnCreate callback.
The first thing to do is create the button, here is what I have:
Button.h
Button.cpp
This is the basic outline for a button. Now, lets create a new instance of it:
Main.cpp
This is pretty basic so far, nothing special happens. Now lets add an event, for when it's created:
Button.h
Button.cpp
Main.cpp
And that is basically how you add a callback in C++. I hope this was understandable and that it makes sense!
Attached is the Visual Studio project.
I'll be explaining how to create and use callbacks.
First, I'll start by explaining what a callback is. A callback is basically a pointer to a function that executes when a certain event
happens. This could be a button click, a window resize, or anything else. For this example, I'll be creating a button class that has an OnCreate callback.
The first thing to do is create the button, here is what I have:
Button.h
Code:
#pragma once
class Button
{
public:
//
// Fields
//
int X;
int Y;
int Width;
int Height;
//
// Functions
//
Button(int x, int y, int w, int h);
};
Code:
#include "Button.h"
Button::Button(int x, int y, int w, int h)
{
X = x;
Y = y;
Width = w;
Height = h;
}
Main.cpp
Code:
#include <stdlib.h>
#include <stdio.h>
#include "Button.h"
int main(int argc, char* argv[])
{
Button* button1 = new Button(5, 5, 100, 26);
printf("button1 created\n");
// So we can see the output. This isn't needed in Visual
// Studio when you start without debugging.
system("PAUSE");
return 0;
}
Button.h
Code:
#pragma once
class Button
{
public:
//
// Fields
//
int X;
int Y;
int Width;
int Height;
// Our callback
void (*OnCreateCallback)(void);
//
// Functions
//
Button(int x, int y, int w, int h, void (*callback)(void));
void OnCreate();
};
Code:
#include "Button.h"
Button::Button(int x, int y, int w, int h, void (*callback)(void))
{
X = x;
Y = y;
Width = w;
Height = h;
OnCreateCallback = callback;
// Trigger the callback
OnCreate();
}
void Button::OnCreate()
{
// Make sure the callback isn't null
if(OnCreateCallback != 0)
{
OnCreateCallback();
}
}
Code:
#include <stdlib.h>
#include <stdio.h>
#include "Button.h"
Button* button1;
void Button1Created()
{
printf("button1 created\n");
}
int main(int argc, char* argv[])
{
// When we call the constructor, we're passing the
// name of the function that handles the OnCreate
// event. If you pass 0, the event won't get called
button1 = new Button(5, 5, 100, 26, Button1Created);
// So we can see the output. This isn't needed in Visual
// Studio when you start without debugging.
system("PAUSE");
return 0;
}
Attached is the Visual Studio project.