开发者

Why does C++ have both classes and structs? [duplicate]

This question already has answers开发者_开发知识库 here: Closed 11 years ago.

Possible Duplicate:

What are the differences between struct and class in C++

If the only difference between structs and classes is the default access specifier(in C++), then why does C++ also have classes?


First, it's backward compatibility with C. Second (and more importantly), it helps describe your intent. The standard convention is that PODs should be denoted with struct and collections of data and behavior should be denoted with class.


You want classes to have the default access specifier to be private when designing object-oriented hierarchies, but structs need to have the default access specifier to be public to preserve compatiblity with C.


Backwards compatibility with C. C didn't have classes, but it had structs.

Note that this is "backwards compatibility" in the text of the .c file only. In C++ structs are really classes, with a default exposure of public instead of a default exposure of private.

class Bob {
   // I haven't overridden the exposure, so it's private
   int age;
   int height;

   public:
     Bob();

};


struct Bob {
   // I haven't overridden the exposure, so it's public
   int age;
   int height;

   // note the constructor defaults to the "default" constructor.
};

A true C style struct is defined as so

extern "C" {
  struct Bob {
     int age;
     int height;
  };
}

In which case age becomes more of an alias of "offset +0" and height becomes more of an alias of "offset +(sizeof(int) + alignment to memory manager boundary) instead of being conceptual fields which can be implemented in any desired manner.


As everyone else has posted, the main difference is default protection level (i.e. public or private). However, it's also a good indication on the actual use of the data structure. For example, sometimes you might want a light-weight structure, similar to a java bean. In that case you might just have:

struct point {
   float x, y;
};

It's clear that you're not using any C++ features here, versus:

class point {
public:
   float x, y;
};

It's less clear what your intention is. I'd likely note the second example as bad code because someone didn't provide getters and setters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜