Skip to content
Advertisement

C++: How can statvfs take a structure of its own type as an input?

I am using statvfs to check the filesystem, and I have difficulties understanding how the following snippet works:

#include <sys/statvfs.h>
struct statvfs aStructure;
int output = statvfs(aPath, &aStructure);
  1. I include the header. This is the only line that’s 100% clear to me here.
  2. I make aStructure of the type statvfs.
  3. I call statvfs with aPath and the structure from the previous step.

In 2. statvfs was a structure, in 3. it appears to be a function returning an int.

Is statvfs(aPath, &aStructure) the statvfs constructor and if so, how come aStructure didn’t need the constructor or are these two different statvfs?

Thank you for helping me untangle my misunderstanding.

Advertisement

Answer

statvfs is a system call, it is not a constructor of any C++ class. struct statvfs is a C structure. C structures do not have constructors.

In C++, struct statvfs becomes a POD. PODs, by definition, do not have constructors.

Your confusion comes from the fact that the name of a structure is exactly the same as the name of a (system call) function. In C++ the lines are blurred, somewhat, when you see the name of what you believe is a class or a structure, you automatically default to thinking that something is being constructed (and it usually is). But this conflation does not exist in C. What you have here is a POD structure, and a system call function that have nothing to do with each other, except that one takes a pointer to the other as a parameter. If you (temporarily) replace in your mind the name struct statvfs with struct blarg, in the shown code, and keep everything else exactly the same, what’s happening here should now be obvious to you.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement