1) What is the use of the scope resolution operator in cases like the following, when we can also define it inline?
In your example, the scope resolution operator is not required when defining a method inside a class:
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void)// Returns box volume
{
return length * breadth * height;
}
};
However, when a function is defined outside of a class, the programmer needs a method to associate a function with a given class. This method needs to differentiate class methods from freestanding functions. Thus the scope resolution operator.
2) Also, the semantics of the line double Box::getVolume(void) is confusing. why couldn’t it have been: double getVolume(void)::Box . Is there some history behind this ?
Actually, the syntax is not confusing when you consider the declaration syntax of a freestanding function:
return_type function_name(function_parameters);
The encompassing namespace or class is associated with the function name, so the syntax is:
return type class_name::function_name(function_parameters);
The definition and declaration may be less confusing if you arrange the pieces differently:
double
Box ::
getVolume(void)
{
return height * length * depth;
}
1
solved scope resolution operator semantics [closed]