mecid
mecid

Reputation: 407

Private Keyword in a C Struct

Today, I have just noticed a statement in a C struct, and to be honest I was like WTF at first. It is like;

struct foo {
void *private;
//Some other members
};

Believe or not this struct is being compiled without any error. So what is the purpose of adding such a line (void *private)?

Upvotes: 0

Views: 368

Answers (3)

Barath Ravikumar
Barath Ravikumar

Reputation: 5836

Actually you have stumbled upon an important difference between C and C++, the way structures are implemented.

In C, structures contains can contain only primitive and composite datatypes, whereas C++ structures gives more functionality, since the structures in C++ are similar to classes than structures in C, hence they provide additional functionality such as

  • Ability to classify members as private,public or protected.
  • Can contain member functions.
  • Structures in C++, can be used as a tool to enforce object oriented methods, since all OO functionality like inheritance, which is applicable to classes , holds good for structures as well.

So in short, the above code is valid C, but invalid C++.

Upvotes: 0

dom0
dom0

Reputation: 7486

void* are in C often used to hide the actual data type used, effectively hiding some implementation details from the interface.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258618

In pure C there's no private keyword, so the above is perfectly legal, albeit a very bad idea.

This would be invalid C++ though, and a C++ compiler would surely yield an error.

Upvotes: 3

Related Questions