Creating global variables in a function C++
<p>I am using C++ and openCV to do people tracking. I am trying to make a function that applies the MOG2 background subtraction method. this is the first time I've tried making a function.
The function looks like this: </p>

<pre><code>Mat FindMOG2(Mat FrameShown){


    MOG2Pointer-&gt;apply(FrameShown, MOG2Mask);

    // find contours
    findContours(MOG2Mask, Contours, Hierachy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));

    //approximate contours to polygons and get bounding rects
    vector&lt;vector&lt;Point&gt; &gt; ContoursPoly(Contours.size());
    vector&lt;Rect&gt; MOGRects(Contours.size());

    for (int i = 0; i &lt; Contours.size(); i++){
        approxPolyDP(Mat(Contours[i]), ContoursPoly[i], 3, true);
        MOGRects[i] = boundingRect(Mat(ContoursPoly[i]));
        }

    //draw bounding rects
    Mat Drawing = Mat::zeros(MOG2Mask.size(), CV_8UC3);

    for (int i = 0; i &lt; Contours.size(); i++){
        vector&lt;Vec4i&gt;(), 0, Point());
        rectangle(Drawing, MOGRects[i].tl(), MOGRects[i].br(), Scalar(0, 255, 0), 2, 8, 0);
        }
    return Drawing;
}
</code></pre>

<p>The problem is, I also have to declare these 'global' variables outside the main()</p>

<pre><code>Mat MOG2Mask;
vector&lt;vector&lt;Point&gt; &gt; Contours;
vector&lt;Vec4i&gt; Hierachy;
Ptr&lt;BackgroundSubtractor&gt; MOG2Pointer;
</code></pre>

<p>and this inside the main, but outside the while loop that plays the video</p>

<pre><code>MOG2Pointer = createBackgroundSubtractorMOG2();
</code></pre>

<p>Basically, I want the function to automatically declare these variables without me having to initialise them. I am new to programming, so if someone could just point me in the right direction or just give me something to research I would be very grateful.</p>

<p>Cheers.</p>