What is a Class

beginner c++11 classes

A class is used to describe a collection of data and functions that work well together. In C++ a class’s data is known as its fields and a class’s functions are known as its methods. There’s two keywords in C++ for declaring a class, class and struct. The only difference between the two is the default access of members. class members are private by default and struct members are public. Typically this means struct will be used for “plain old data” without any functions or private data and class will be used for “objects” with methods, private data, and invariants. There really isn’t any hard and fast rule though and everything a class can do a struct can do as well in C++.

#include <iostream>

struct Affection {
  int rubs = 0;
  int pats = 0;
  int scritches = 0;

class Dog {
    void pet(const Affection& affection) {
      happiness += 1 * affection.rubs;
      happiness += 2 * affection.pats;
      happiness += 3 * affection.scritches;

    void bark() {
      if (happiness <= 50) {
        std::cout << "woof\n";
      } else {
        std::cout << "WOOF WOOF!\n";
    int happiness = 40;

int main() {
  Dog dog;

  Affection affection;
  affection.rubs = 2;
  affection.pats = 4;
  affection.scritches = 3;


For more C++ By Example, click here.