double-colon (::) before method declaration in class definition

892 views Asked by At

I have a class written by a 3rd party, which has something like this Foo.h:

class Foo
{
public:
    int Foo::dosomething(float x, float y, float z);

    //Other things here
};

And in Foo.cpp, dosomething is:

int Foo::dosomething(float x, float y, float z)
{    
    //Something
}

What does the :: before the function name in the header mean? When I create a new object

Foo foo;

I cannot access the dosomething function like this:

foo.dosomething(1,2,3);

How is dosomething meant to be accessed? When I remove the :: in the header file before dosomething like so:

class Foo
{
public:
    int dosomething(float x, float y, float z);

    //Other things here
};

I can access dosomething from an object of type Foo.

2

There are 2 answers

0
jxh On BEST ANSWER

In general, it is not illegal to use the :: scope operator against the existing class scope to refer to its own members (even though it is redundant).

After the point of declaration of a class member, the member name can be looked up in the scope of its class. [ Note: this is true even if the class is an incomplete class. For example, struct X {
enum E { z = 16 };
int b[X::z];         // OK
};
C++11 §3.3.2 ¶5

The problem is that the definition of point of declaration seems to preclude using the scope operator in the member declaration if it is on its own name.

The point of declaration for a name is immediately after its complete declarator (Clause 8) and before its initializer (if any), except as noted below. [ Example:
int x = 12;
{ int x = x; }
Here the second x is initialized with its own (indeterminate) value. — end example ]
C++11 §3.3.2 ¶1

There are no exceptions for class members in the paragraphs that follow in the rest of §3.3.2.

Even with the above restriction, the syntax for class members do not prohibit the use of a qualified-id for the member name. It is therefore not a syntax error to accept the shown code. But, there is a semantic violation, and a diagnostic should have been emitted.

0
Cory Kramer On

It is incorrect (and many compilers consider it an error) to add the scope to the function name within the class definition. Since it is already within the scope of a class, you are essentially defining the functions scope as Foo::Foo::dosomething which is wrong.

class Foo
{
public:
    int Foo::dosomething(float x, float y, float z);   // Shouldn't have Foo::
};

To answer your question of what the :: does, it specifies the scope of the function. Consider these two functions

int dosomething(float x, float y, float z);
int Foo::dosomething(float x, float y, float z);

The first is a free function, the latter is a method of the Foo class and (since it isn't preceded by the word static) requires an instance of Foo to be called from.