Overview

This tutorial provides an introduction to C++ classes using a simple example.

We will cover the basics of class definitions, member variables, member functions, constructors, and destructors.


Code Example

Let's start with the complete code:


Explanation

Class Definition

A class is a user-defined type that holds its own data members and member functions. The MyClass class is defined as follows:

class MyClass {
  // Class members and methods
};

Access Specifiers

Access specifiers define the accessibility of the class members. They can be private, protected, or public. We'll have a dedicated session on access specifier. Basic rules are provided below.

private:
  string name; // private member variable

public:
  void sayHi(); // public member function
};

Member Variables

Member variables are the data attributes of a class. In this example, name is a private member variable of type string.

string name;

Member Functions

Member functions are the functions that operate on the data members of the class. The sayHi function prints a greeting along with the name.

void sayHi() {
  cout << "Hi " << name << endl;
}

Constructor

A constructor is a special member function that is automatically called when an object of the class is created. The MyClass constructor initializes the name member variable and prints a message.

MyClass(string name) {
  cout << "MyClass constructor called" << endl;
  this->name = name;
}

Destructor

A destructor is a special member function that is automatically called when an object of the class is destroyed. The ~MyClass destructor prints a message.

~MyClass() {
  cout << "MyClass destructor called" << endl;
}

Main Function

The main function is the entry point of the program. It creates an instance of MyClass with the name "Jake", calls the sayHi function, and returns 0 indicating successful execution.

int main() {
  MyClass myObject("Jake");
  myObject.sayHi();
  return 0;
}

Output

When the program is executed, you see the output as shown below. This sequence happens as the object myObject is created, used, and then destroyed.

MyClass constructor called
  Hi Jake
  MyClass destructor called