c sharp Logo

Classes and Objects


A class in C++ is a blueprint for creating objects. A class defines the structure of an object, including the data that it contains and the methods that it can perform.

An object is an instance of a class. It is a self-contained entity that contains both data and code.

Example

The following code shows a simple class named Person:

class Person {

public:

  Person(std::string name, int age) {

    this->name = name;

    this->age = age;

  }

 

  std::string GetName() {

    return name;

  }

 

  int GetAge() {

    return age;

  }

 

private:

  std::string name;

  int age;

};

 

This class has two data members, name and age, and two methods, GetName() and GetAge().

To create an object of the Person class, you use the following syntax:

Person person("John Doe", 30);

 

This creates a new Person object and initializes the name and age data members to the specified values.

You can then access the data members and methods of the object using the dot operator (.). For example:

std::string name = person.GetName();

int age = person.GetAge();

 

This code gets the name and age of the person and stores them in the variables name and age, respectively.

Benefits of using classes and objects

There are several benefits to using classes and objects in C++, including:

  • Modularity: Classes allow you to encapsulate data and code within objects, which makes your code more modular and reusable.
  • Abstraction: Classes allow you to abstract away the implementation details of objects, which makes your code easier to understand and maintain.
  • Code reuse: Classes allow you to reuse code by creating new classes that inherit from existing classes.
  • Flexibility: Classes make your code more flexible by allowing you to write code that can be used with different types of objects.

Conclusion

Classes and objects are a fundamental part of C++. By understanding how to use classes and objects, you can write more modular, reusable, flexible, and maintainable code.