top of page

Useful C++ Code Snippets


Source: xkcd.com

Again for my Fall 2018 C++ course at CMU. These are snippets of code that I use a lot and want to remember.

Main function (which keeps graphics window open until Esc key is hit):

int main(void)

{

FsOpenWindow(x, y, width, height, 1);

FsRegisterOnPaintCallBack(Render, nullptr);

while (FSKEY_ESC != FsInkey())

{

FsPollDevice();

FsPushOnPaintEvent();

FsSleep(10);

}

FsCloseWindow();

return 0;

}

Graphics render function:

void Render(void *)

{

glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

FsSwapBuffers();

}

Creating a Class:

class Foo

{

protected: <not directly accessible from outside class!>

<list variables and functions here>

public:

<list variables and functions here>

void func_foo(const var_foo) const; // this is a constant function with a constant variable

void constructor(); // constructor function for the class

void ~destructor(); // destructor function for the class

void CleanUp(); // clean up releases memory used by the class

};

Foo::constructor()

{

}

Foo::~destructor()

{

CleanUp();

}

Foo::CleanUp()

{

}

Drawing Lines:

glColor3ub(r, g, b); glBegin(GL_LINES); glVertex2i(x1, y1); glVertex2i(x2, y2); glEnd();

Dynamically Allocating Memory to an Array:

char *array;

array = new char[size];


bottom of page