Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring variable inside functions of a class in C++

MyFill is a class and MyFill2 is a function inside that class.

What is the difference in between declaring a variable inside public function of the class like this (thickness and lineType) -->

MyFill::MyFill (Mat img, Point center)
{
    MyFill2 (img, center);
}

void MyFill::MyFill2(Mat img, Point center)
{
    int thickness = -1;
    int lineType = 8;
    circle (
        img,
        center,
        w/32,
        Scalar( 0, 0, 255 ),
        thickness,
        lineType
    );
}

...and just declaring them in private label (private:), like in the header file -->

class MyFill {
public:
    MyFill(Mat img1, Point center1);
    void MyFill2 (Mat img, Point center);
private:
    int thickness = -1;
    int lineType = 8;
};

The first one works right. But the second one doesn't. If I want to go with the second option, what I need to do? A right code with some explanation might help.

like image 328
ridctg Avatar asked Jul 24 '13 11:07

ridctg


1 Answers

You are not allowed to assign values to variables inside the scope of the class, you can only do this inside of a function, or in the global scope.

class MyFill {
public:
MyFill(Mat img1, Point center1);
void MyFill2 (Mat img, Point center);
private:
int thickness;
int lineType;
};

Your header needs to be changed to the above. You then set your values in any function you like, preferably your constructor like so:

MyFill::MyFill(Mat img1, Point center1)
{
     thickness = -1;
     lineType = 8;
}

Edit - To your question in the comments:

Identifiers for variable names in function parameters do not need to match between declaration and definition, only the types and their order need to match. It makes it more clear, but its not required.

A function prototype is really only seen as the following:

void MyFill2(Mat, Point);

When you give it a definition, that is when the assignment of identifiers really matters:

void MyFill2(Mat m, Point p)
{
    //....
}
like image 99
Joseph Pla Avatar answered Sep 23 '22 23:09

Joseph Pla