In C++, an array of objects can be created by declaring an array where each element is an object of a specific class. Here's a simple example:


#include <iostream>

#include <string>

class MyClass {

public:

    int id;

    std::string name;

    MyClass(int i, const std::string& n) : id(i), name(n) {}

};


int main() {

    const int arraySize = 3;

    MyClass myObjects[arraySize] = { {1, "Object1"}, {2, "Object2"}, {3, "Object3"} };

    for (int i = 0; i < arraySize; ++i) {

        std::cout << "Object " << myObjects[i].id << ": " << myObjects[i].name << std::endl;

    }

    return 0;

}


In this example, `MyClass` is a simple class with an `id` and a `name`. An array of `MyClass` objects is created in the `main` function, and each object is initialized with specific values. You can then access and manipulate these objects like any other array elements.


Note that C++ also provides dynamic arrays using pointers or containers like `std::vector` if you need more flexibility in the size of your array at runtime.

Comments

Popular posts from this blog

FCPIT

OOP Using C++