Answer the question
In order to leave comments, you need to log in
ClassName::functionName or objectName.functionName?
Hi all!
I am learning C++ and I have a question.
Why do we sometimes use a construct like ClassName::functionName and sometimes objectName.functionName ? Those. for example, in the file with main we specify the second option, and in the file with the function logic we use the first option? What does it depend on.
I understand that cout << objectName.functionName means that we output the return data of a function that belongs to a class object (operates with object data).
But that's why we sometimes use cout << ClassName::functionName instead of the first option, I can't figure it out...
Thanks in advance!
Answer the question
In order to leave comments, you need to log in
I will answer without guesswork.
> I understand that cout << objectName.functionName means that we output the return data of a function that belongs to a class object (operates with object data).
This is well consistent with the truth, in general, there is nothing to add.
> But that's why we sometimes use cout << ClassName::functionName instead of the first option, I can't figure it out...
"::" is the scope extension operator. In C++, different entities can be declared "inside" other entities. For example, functions inside classes, as in your case - then they become methods. Classes, functions and variables can be declared inside namespaces. Classes can be declared within other classes. Classes can even be declared within function definitions.
In all these and other cases, we can talk about two entity names - a short one, which is unique within the parent entity, and a full one, by which the entity can be accessed from anywhere in the program. For example,
namespace MyLibrary {
namespace UI {
class Widget {
///
};
class Controller {
private:
Widget *widget; // Здесь Widget будет видно по короткому имени
};
}
}
namespace App {
MyLibrary::UI::Widget *w; // А вот здесь уже нужно использовать полное
}
through a dot is a call to the function of the object.
and through a double colon - this is an indication of the scope seems.
for example
, here is an indication of the scope of the function, well, or the class std. probably it is 1 such object of class std.
but this is all guesswork.
ClassName::functionName and sometimes objectName.functionName
#include <iostream>
using namespace std;
class Test
{
public:
static void st() { cout << "static" << endl; }
void nonst() {cout << "non static" << endl; }
};
int main(int argc, char **argv)
{
Test t;
Test::st(); // для статик метода можно так
t.st(); //и так тоже можно
Test::nonst(); // compilation error: так нельзя для не статик метода
t.nonst(); //можно только так
system("pause");
return 0;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question