C++ Tutorial

C++ Classes and Objects

class names a type. Creating a variable of that type makes an object.

class names a type

The keyword class starts a type definition. Inside the class you list members: fields (data) and, later, methods (functions). After the closing brace you need a semicolon. Forget that semicolon and g++ will complain in a confusing way, often on the next line.

Once the class exists, its name works like int or string. You declare a variable of that type. That variable is an object.

Public members

public: means code outside the class can read and write those members. For a first class, put the fields in the public section so main can set them. The next chapters hide fields on purpose. Here the goal is to see an object hold values.

Example

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

class Player {
 public:
  string name;
  int score;
};

int main() {
  Player p;
  p.name = "Rin";
  p.score = 10;
  cout << p.name << " " << p.score << endl;
  return 0;
}

p.name and p.score use the dot operator. The object is p. The member is the name after the dot.

Creating an object

Player p; creates one object. It has its own name and its own score. Until you assign them, their values are not something you should print. Always set public fields before you use them, or use a constructor (next but one chapter).

Player is the type. p is the object. Writing Player again does not create another object; it is just the type name. You need another variable for a second player.

Two objects

Each object has its own copy of the fields. Change a.score and b.score stays the same. That is the point of a type: one blueprint, many independent values.

Example

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

class Player {
 public:
  string name;
  int score;
};

int main() {
  Player a;
  a.name = "Rin";
  a.score = 10;

  Player b;
  b.name = "Kai";
  b.score = 14;

  cout << a.name << " " << a.score << endl;
  cout << b.name << " " << b.score << endl;
  return 0;
}

Run this in /cpp/try. Set a.score = 99 after both objects exist and print again. Only Rin's score changes.

Members are per object

Think of the class as a row layout: a string and an int. Each object is one row. a andb do not share name. If you wanted a shared value, that would be a static member — skip that until you are comfortable with ordinary fields.

Objectnamescore
aRin10
bKai14

A class is not a struct lesson

struct in C++ can do almost the same thing. The difference beginners care about: class members start private unless you write public:. struct members start public. This tutorial usesclass for types that will grow methods and access rules. Next: functions that belong to the class.

Example

#include <iostream>
using namespace std;

class Box {
 public:
  int w;
  int h;
  int area() {
    return w * h;
  }
};

int main() {
  Box floor;
  floor.w = 4;
  floor.h = 3;
  cout << "area: " << floor.area() << endl;
  return 0;
}

Worked examples

The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.

Open them in the C++ editor at /cpp/try. Change one measurement and check whether the result still has the right unit.

Physics

A 2D vector class

Position, velocity, and force in a plane are all pairs of doubles. A Vector type gives that pair a short name. |v| for (3, 4) is 5, the same geometry as every other 3-4-5 in this course.

|v| = √(x² + y²)

Example

#include <iostream>
#include <cmath>
using namespace std;

class Vector {
public:
  double x;
  double y;
  double mag() { return hypot(x, y); }
};

int main() {
  Vector v;
  v.x = 3.0;
  v.y = 4.0;
  cout << "|v| = " << v.mag() << endl;
  return 0;
}

Chemistry

A solution with volume

Concentration is amount over volume. 0.10 mol in 0.250 L is 0.40 mol/L. The class holds both numbers so molarity() cannot mix two different flasks.

c = n / V

Example

#include <iostream>
using namespace std;

class Solution {
public:
  double moles;
  double litres;
  double molarity() { return moles / litres; }
};

int main() {
  Solution flask;
  flask.moles = 0.10;
  flask.litres = 0.250;
  cout << flask.molarity() << " mol/L" << endl;
  return 0;
}

FAQ: C++ Classes and Objects

Common questions about this page.

What is the StudyGrid C++ tutorial?

The StudyGrid C++ tutorial is a full beginner-to-advanced track: syntax, types, input, loops, functions, classes, the STL, templates, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run c++ classes examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn c++ classes in this C++ C++ lesson (C++ Classes and Objects).

Is the C++ editor the same as Try Python or Try HTML?

No. Try C++ compiles with g++ at /cpp/try and shows stdout plus compiler messages. Try Python stays at /try. Try HTML stays at /html/try. C++ lessons never open those editors.

Do I need to install a compiler to learn C++?

No. Open a chapter, click Try it in C++, and compile in the browser. You can also download a .cpp file and compile locally with g++.

Where should I start the C++ tutorial?

Start at C++ Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open C++ Examples, then templates, map, and lambdas. Use Next at the bottom of each chapter.

Is the C++ tutorial free?

Yes. The C++ workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.