๐ŸŽ“ A1Learner
๐Ÿ”

C++ Classes

A class is a type that groups data and methods together. A method is a function that belongs to a class.

A class with a method

The Robot class holds a name and a greet method. The method prints a line using the name member.

#include <iostream>
#include <string>

class Robot {
public:
  std::string name;
  void greet() {
    std::cout << "Hello, I am " << name << std::endl;
  }
};

int main() {
  Robot r;
  r.name = "Pip";
  r.greet();
  return 0;
}

Two objects, separate values

Both objects come from the Robot class. Each greet call prints the name held by its own object.

#include <iostream>
#include <string>

class Robot {
public:
  std::string name;
  void greet() {
    std::cout << "Hello, I am " << name << std::endl;
  }
};

int main() {
  Robot first;
  first.name = "Pip";
  Robot second;
  second.name = "Milo";
  first.greet();
  second.greet();
  return 0;
}

A method changes a member

The step method adds 1 to the count member. Two calls leave the count at 2.

#include <iostream>

class Counter {
public:
  int count = 0;
  void step() {
    count = count + 1;
  }
};

int main() {
  Counter c;
  c.step();
  c.step();
  std::cout << c.count << std::endl;
  return 0;
}

Example

#include <iostream>
#include <string>

class Dog {
public:
  std::string name;
  void speak() {
    std::cout << name << " says Woof" << std::endl;
  }
};

int main() {
  Dog first;
  first.name = "Rex";
  Dog second;
  second.name = "Luna";
  first.speak();
  second.speak();
  return 0;
}

Key points

  • Use class to define a class and its members.
  • public: opens the members listed under it.
  • A data member holds a value inside an object.
  • A method is a function defined inside a class.
  • Use a dot to reach a member or call a method of an object.
  • Each object holds its own member values.

In this example, the Dog class holds a name member and a speak method. Each object gets its own name after it is made. Each speak call prints the name held by its own object.

Note

Members can be set after the object is made, and a method can then use those values.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C++ Compiler

Exercise

How does main call the speak method of a Dog object named d?