Skip to the page

Classes and objects · core

Classes, structs and access

A class keeps data and the functions that keep it valid together. In C++ the only difference between class and struct is the default access.

The notes

What you must know

  • public: anyone can use it. private: only the class's own member functions and its friends. protected: also the classes derived from it.
  • In a class, members and base classes are private by default. In a struct they are public by default. That is the only difference between them.
  • Encapsulation: keep data private and change it only through member functions that check it. setMarks(int m) rejects values outside 0 to 100, for example by throwing std::invalid_argument.
  • Check in the constructor too, so an object can never start in a bad state. Not every member needs a setter: a roll number can be const and set once.
  • A member function gets a hidden pointer, this, to the object it was called on. this->marks = marks; sets the member when a parameter has the same name.
  • A const member function, int getMarks() const, promises not to change the object. Only const member functions can be called on a const object or through a const reference.
  • A friend function or friend class can use private members. It is not a member and has no this. Use it rarely, for example for operator<<.
  • An object's size comes from its data members (plus padding, and a hidden pointer if it has virtual functions). Member functions are stored once, not in every object.

The red pen

Common traps: mistake → fix

  • Mistake: A struct cannot have member functions or private members

    Fix: in C++ a struct is a class with public default access.

  • Mistake: protected means the same as private

    Fix: derived classes can use protected members.

  • Mistake: Private fields with a setter for each is encapsulation

    Fix: a setter must check the value, or nothing is protected.

  • Mistake: A const object can call any member function

    Fix: only const member functions.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the difference between a class and a struct in C++?
  2. In your project, marks are sometimes set to -50. How do you stop it with a class?
  3. What do public, private and protected mean?
  4. What is a const member function, and why does it matter when you pass const Student&?
  5. What is a friend function? When would you use one?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview