Ad
Why Do You Use A Scope Resolution Operator When Defining A Class' Method?
My question about the Scope Resolution Operator (::) is why do we use it in a CPP file to define the methods of a class? I'm more so asking about the SRO itself, rather than the relationship between CPP and Header files.
Ad
Answer
When you define a class:
struct foo {
void bar() {}
};
Then the full name of bar
is ::foo::bar
. The leading ::
to refer to the global namespace can often be omitted. There is no bar
in the global namespace, hence bar
alone (or ::bar
) does not name an entity and when you define the method out of line you need to tell what bar
you mean:
struct foo {
void bar();
};
struct baz {
void bar();
};
void bar() {} // this defines a completely unrelated free function called bar
void foo::bar() {} // defines foo::bar
void baz::bar() {} // defines baz::bar
You need the scope resolution operator to state which method you want to define.
For more details I refer you to https://en.cppreference.com/w/cpp/language/lookup
Ad
source: stackoverflow.com
Related Questions
- → Comparing two large files are taking over four hours
- → Setting JSON node name to variable value
- → Compiling GLUT using Emscripten
- → Evaluate check box from a scanned image in node.js
- → Find an easy web server framework for mobile game
- → my https C++ code doesn't work on some sites (binance)
- → Error while opening pivx wallet on ubuntu
- → Why sending a POST by AJAX is interpreted by the HTTP Server as OPTIONS and sending by CURL is effectively a PUT?
- → Python reading in one line multiple types for a calculator
- → How do I properly pass an argument to a function
- → Accessing Websql database with Qt
- → Using Mysql C API for c++ codes
- → How do I set constants at run-time in a c++ header file, imported through Cython?
Ad