Small Steps II — Making Things

Open and Use a Window

Open and Use a Window

Explore one topic in small steps. Try the examples one at a time and take a break whenever you need. Choose how many extra exercises you want to try.

Opening a window

What you will learn

Window is a type for working with a window on the screen. An object is an actual instance of that type. Create an object named window and open a window.

Try it

Example · example1.cpp
void small_main()
{
    Window window;
    window.set_title("My First Window");
    window.open(640, 480);

    while (window.is_open())
    {
        window.show();
    }
}

open(640, 480) opens a window 640 pixels wide and 480 pixels high. A pixel is a small dot making up the screen. set_title sets the title.

Repeat show while is_open is true. show displays the screen and handles input such as closing the window. This call is needed for the window to respond. The loop ends when you press its close button.

Later drawing examples reuse this window-opening structure.

Asking an object for information

What you will learn

Writing a function name after an object's dot uses an operation belonging to that object. Such a function is a member function.

Try it

Example · first_window_2_example2.cpp
void small_main()
{
    Window window;

    window.set_title("Small Window");
    window.open(400, 300);

    print("Size: ", window.width(), " x ", window.height());

    while (window.is_open())
    {
        window.show();
    }
}

window.width() and window.height() return the window's width and height. Check that the console shows Size: 400 x 300.

Creating the object and opening the actual window are separate actions. You can call set_title before open. Call close to close it from your program.

Exercise

Open a 500 × 300 Window and set its title to your name. Keep it open until it is closed.

Exercise starter · exercise1_starter.cpp
void small_main()
{
    Window window;

    // Set a title and open a 500 x 300 window.
}

Hint

You can call set_title before open too.

show solution
void small_main()
{
    Window window;
    window.set_title("Alex");
    window.open(500, 300);

    while (window.is_open())
        window.show();
}
Try More (Optional)

Exercise

Open a 320 × 240 window, print its actual width and height in the console, and keep the window open.

Exercise starter · first_window_2_exercise2_starter.cpp
void small_main()
{
    Window window;
    window.open(320, 240);

    // print the size, then keep the window alive.
}

Hint

Pass window.width() and window.height() to print.

show solution
void small_main()
{
    Window window;
    window.open(320, 240);

    print(window.width(), " x ", window.height());

    while (window.is_open())
        window.show();
}
← Previous lessonNext lesson →