Objects

In C++, an object is an instance of a class. A class is a blueprint or template that defines the structure and behavior of objects. Objects are used to encapsulate data and functions (methods) that operate on that data. Here's an example of defining a class and creating objects in C++:

#include <iostream>

// Define a simple class called "Person"
class Person {
public:
    // Constructor to initialize the object
    Person(std::string name, int age) : name_(name), age_(age) {}

    // Member function to display information about the person
    void DisplayInfo() {
        std::cout << "Name: " << name_ << ", Age: " << age_ << " years" << std::endl;
    }

private:
    // Private member variables
    std::string name_;
    int age_;
};

int main() {
    // Create objects of the Person class
    Person person1("Alice", 30);
    Person person2("Bob", 25);

    // Call member functions on objects
    person1.DisplayInfo();
    person2.DisplayInfo();

    return 0;
}

In the code above:

  1. We define a class called Person with a constructor, a member function DisplayInfo, and private member variables name_ and age_. The constructor initializes the object with a name and age.

  2. In the main function, we create two objects, person1 and person2, of the Person class using the constructor.

  3. We then call the DisplayInfo member function on each object to display their information.

Objects encapsulate data (in this case, name_ and age_) and the functions that operate on that data (e.g., DisplayInfo). Objects of the same class share the same methods but have their own unique data.

Last updated

Was this helpful?