Skip to content
Justice Tech School

Classes and Objects

A class holds data members and member functions. public members are accessible from outside and private ones only inside the class. A constructor sets up an object and a destructor cleans up. Use const on member functions that do not change the object.

Example
#include <iostream>
#include <string>
using namespace std;

class Student {
 private:
  string name;
  int score;
 public:
  Student(string n, int s) : name(n), score(s) {}
  void addPoints(int p) { score += p; }
  string describe() const { return name + " has " + to_string(score); }
};

int main() {
  Student s("Ada", 70);
  s.addPoints(5);
  cout << s.describe() << endl;
}

Result

Ada has 75

Exercise

Make a member visible outside the class.

class A { : int x; };

Quiz Test

What does private mean?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.