Turbo C++ can also host a variety of graphics functions using its very own <graphics.h> header file!
We can start by adding our including <graphics.h> in our source code:
#include <graphics.h>
#include <conio.h>
main () {
// statements go here;
return 0;
}The header file contains a lot of useful functions in Turbo C++ that allows us to produce graphics that can be more visually appealing than console text.
We will discuss it in the next few sections.
Initializing the Graphics Driver
To start using graphics functions, we first initialize the graphics driver.
To do this, we set up two variables gd and gm for the graphics driver and the graphics mode respectively.
We then initialize gd as DETECT.
This tells the graphics driver to detect the best driver to use.
main () {
int gd = DETECT, gm;
return 0;
}Starting Graphics Mode
Once the driver is initialized, we can now start graphics mode.
In Turbo C++, graphics functions cannot be executed unless we tell the compiler to switch to graphics mode.
To do this, we call the initgraph() function and pass the location of gd and gm as its parameters.
main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "C://TURBOC3//BGI");
// graphics functions go here
closegraph();
getch();
return 0;
}Notice that in the third argument, it indicates the folder where your graphics driver is located.
This is the path where the BGI folder is located, which is included in your Turbo C++ installation.
Finally, we close the graph by calling the closegraph() function.
We also ensure that upon closing the graph, we use getch() as it will immediately close the program upon closing.
Modular Graphics
While the above is more ideal for simple projects, we might want to be more modular, such as breaking our code as functions.
In such cases, we can initialize our graphics like this:
struct GraphicsConfig {
int gd;
int gm;
}
void startGraphics (GraphicsConfig &gs) {
gs.gd = DETECT;
initgraph(&gs.gd, &gs.gm, "C://TURBOC3//BGI");
}
void endGraphics () {
closeGraph();
}
main() {
GraphicsConfig gc;
startGraphics(gc);
// graphics functions go here;
endGraphics(gc);
getch();
return 0;
}This allows us to easily work with graphics in multiple functions, which allows us to separate code for menus, for the actual program, or for other miscellaneous stuff.