Search code examples
c++umlpublicclass-diagramprotected

Protected method in UML diagram?


I have the following UML showing how to create a class Point2D.

enter image description here

I have created a header file for this class based on the UML:

#ifndef Point2D_h
#define Point2D_h

using namespace std;

// Header file for class Point2D

class Point2D
{
    protected:
        int x;
        int y;
        double distFrOrigin;
        setDistFrOrigin();
    
    public:
        Point2D()
        {
            x = 0;
            y = 0;
        }

        Point2D(int xInput, int yInput)
        {
            x = xInput;
            y = yInput;
        }

        int getX();
        int getY();
        double getScalarValue();
    
        int setX(int x);
        int setY(int y);    
};

#endif

However, I am confuse on the method setDistFrOrigin(). The method is located inside the UML operation and it is a protected method. Am I suppose to group it with the protected in my class? Or is there a way to declare protected in the public block in the class? What should be the correct way?


Solution

  • Total freedom

    C++ gives you total freedom for this. You may for example:

    • group the members by access specifier. You could inside a section optically group variables and functions;
    • group the members à-la UML, with variables on one side and functions on the other, having each time a private, protected and public section.

    Additional remarks

    • Style is a matter of personal taste and being consistent is more important than chosen style. Therefore in a team always adopt the team's style.
    • Keep in mind, that someone will have to maintain the code and an access specifier might be easily overlooked when scrolling back and forth. 3 or 4 sections are manageable. If you have 6 sections, or even 12 in case of static members, it starts to become hard to read.
    • This other SO question is more general about ordering of members. It shows that there are many opinions, and that besides data and functions, there are also constants and types.
    • A widely accepted recommendation is to put the public part fist (see Bruno's comment + C++ Core Guideline, Google coding standards, and similar style guide). Nevertheless, if you've learned C++ with Stroustrup's older books, you wouldn't be shocked to have all the private data then functions at the beginning, and only a public keyword in the middle of the class followed by mostly functions, which is not so far from the UML layout)

    Not related: