C++ - Class

In object-oriented programming, a class is a blueprint or template that defines the properties (data members) and behaviors (member functions) of objects. It provides a structure for creating objects of the same type.

An object, on the other hand, is an instance of a class. It represents a specific entity or element that can be manipulated and interacted with in a program. Objects have their own unique set of data and can perform actions based on the behaviors defined in the class.

To better understand the concept, let's use an example of a class called Car:

class Car {
private:
    std::string brand;
    std::string model;
    int year;
public:
    void setBrand(const std::string& newBrand) {
        brand = newBrand;
    }
    void setModel(const std::string& newModel) {
        model = newModel;
    }
    void setYear(int newYear) {
        year = newYear;
    }
    void displayInfo() {
        std::cout << "Brand: " << brand << std::endl;
        std::cout << "Model: " << model << std::endl;
        std::cout << "Year: " << year << std::endl;
    }
};

In this example, the Car class has three private data members (brand, model, and year) and four member functions (setBrand(), setModel(), setYear(), and displayInfo()). The private data members can only be accessed within the class, while the public member functions can be accessed from outside the class.

To create objects of the Car class, you can declare variables of the class type, as shown below:

Car car1;
Car car2;

In this case, car1 and car2 are objects of the Car class. Each object has its own set of data members (brand, model, and year) and can invoke the member functions defined in the Car class.

You can then manipulate the objects and access their members using the dot (.) operator, like this:

car1.setBrand("Toyota");
car1.setModel("Camry");
car1.setYear(2020);
car1.displayInfo();
car2.setBrand("Ford");
car2.setModel("Mustang");
car2.setYear(2018);
car2.displayInfo();

In this example, the setBrand(), setModel(), and setYear() functions are used to set the values of brand, model, and year for each car object. The displayInfo() function is then called to display the information of each car object.