C++ Classes and Objects

Classes and Objects in PHP

Classes and objects are two of the core features of object-oriented programming. A class is a blueprint for creating objects, while an object is an instance of a class.

Let’s look at an example of declaring and using a class:

#include <iostream>

class Person
{
private:
    std::string name;
    int age;
 
public:
    Person(std::string name, int age)
    {
        this->name = name;
        this->age = age;
    }
 
    void printInfo()
    {
        std::cout << "Name: " << name << std::endl;
        std::cout << "Age: " << age << std::endl;
    }
};
 
int main()
{
    Person person("John", 25);
    person.printInfo();
 
    return 0;
}

Output

Name: John
Age: 25

In this example, we have declared a class called Person and defined a constructor and a printInfo() method. We have then created an instance of the Person class and used the printInfo() method to print out the name and age of the person.

Leave a Reply