-1

In C programming, What does this colon do in struct?

struct ABC:XYZ {int num;}

where XYZ is also a struct. This does not seem to be a bitfield. What does ':' mean here?

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
  • 5
    Inheritance. ABC inherits from XYZ – yizzlez Aug 12 '15 at 21:04
  • Do not add C tag for C++-only questions. That is no valid C construct, but C++ class inheritance. – too honest for this site Aug 12 '15 at 21:04
  • @Olaf: The OP obviously thought that this was a C question. The first line even says, "In C programming, [...]". So the real problem is the accidentally-correctly tagging it with C++. – ruakh Aug 12 '15 at 21:05
  • Ok, so he confuses C++ with C. Ok, it'll take back the harsh sound off my comment, but leave the rest as a friendly hint. (OTOH: if he thought that was C, why adding C++ tags?) – too honest for this site Aug 12 '15 at 21:05
  • thanks everyone! right, I thought it was C. And even in C++, I did not know struct can inherit from another struct. It's good to know. – user2014033 Aug 12 '15 at 21:25
  • @user2014033: It's because in C++, there isn't really such a thing as a struct; `struct` is just a synonym for `class`, except with an implicit `public:` instead of an implicit `private:`. – ruakh Aug 13 '15 at 23:34

2 Answers2

2

The code:

struct ABC:XYZ {int num;}

means "define a struct ABC which inherits from XYZ and has a num member of type int. Specifically the : means "inherits from".

That code is equivalent to:

struct ABC : public XYZ {int num;}

For structs the default inheritance visibility is public, for classes it's private.

Shoe
  • 74,840
  • 36
  • 166
  • 272
2

When inherit you usually write:

class Child : public Parent { ... };

you can also write

class Child : Parent { ... };

but for class that would be private inheritance, so you usually see keyword public there. Same for struct except if not specified explicitly it would be already public.

Slava
  • 43,454
  • 1
  • 47
  • 90