[C++ job interview Q&A] The differences between struct and class.

Today’s topic seems to be straightforward… and actually it could be shorter than that. 🙂

There’s only one technical difference between struct and class – their access modifiers are different by default.
If no access modifier is specified, all members of a struct are public. In case of a class, the members are private by default. This rule concerns default inheritance access modifier, too, respectively.

And that’s it! Both classes and structs can contain fields, methods, special member functions, e.g. constructors, assignment operators, etc. They both can also participate in inheritance.

Let’s think more… What do you express by using a struct and a class? Why in some cases you decide to use one and not the other? We should think through, what are the actual meanings of these constructs? This is actually the clue of this topic.

A struct is a pack of variables, tied up in a certain context. For example, this could be a pack of parameters passed to a function or a pack of outputs from a function.

// Good example of a struct.

struct Result
  int code;
  const char* message;

In this context, a class is completely different from a struct. It’s focused on functions, it has an interface, internal state and responsibilities. It’s distinguished by its implementation details and invariants.

// Good example of a class.

// Class responsible for parsing xml file.
class Configuration
  // Interface of a class.
  explicit Configuration(const std::string& filePath);
  std::any get(const std::string& key) const noexcept;

  std::map<std::string, std::any> m_map; // Implementation details

Tagged in
Leave a reply