Classes & Objects

Lesson 27
Author : Afrixi
Last Updated : November, 2022
C++ - Programming Language
This course covers the basics of programming in C++.

In C++, classes are used to define custom data types that encapsulate data and behavior into a single unit. An object is an instance of a class, and it contains its own set of data and functions.

Here’s an example of how classes and objects can be used in C++:

#include <iostream>
#include <string>

class Person {
public:
  // constructors
  Person() {}
  Person(std::string n, int a) : name(n), age(a) {}
  
  // getters and setters
  std::string getName() { return name; }
  void setName(std::string n) { name = n; }
  int getAge() { return age; }
  void setAge(int a) { age = a; }
  
  // other member functions
  void sayHello() {
    std::cout << "Hello, my name is " << name << " and I am " << age << " years old." << std::endl;
  }
  
private:
  std::string name;
  int age;
};

int main() {
  // create an object of the Person class
  Person p1("Alice", 25);
  
  // call member functions on the object
  p1.sayHello();
  p1.setName("Bob");
  p1.setAge(30);
  p1.sayHello();
  
  return 0;
}

In this example, we define a Person class with a constructor that takes a name and age, as well as getters and setters for the name and age data members. We also define a member function sayHello that prints a greeting with the person’s name and age.

In the main function, we create an object p1 of the Person class with the name “Alice” and age 25. We then call the sayHello function on the object, which prints a greeting with Alice’s name and age. We then use the setName and setAge functions to change the name and age of the object, and call the sayHello function again to print a greeting with the updated values.

Classes and objects are powerful tools in C++ that allow us to organize and structure our code, encapsulate data and behavior, and create reusable and extensible code.