Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,907 questions

51,839 answers

573 users

How to initialize array of objects using constructor in C++

2 Answers

0 votes
#include <iostream>

class Test {
    int x, y;
public:
    Test() = default;
    Test(int a, int b) : x(a), y(b) {}

    void print() const {
        std::cout << "x = " << x << " y = " << y << "\n";
    }
};
int main() {
    Test *arr = new Test[5];

    for (int i = 0; i < 5; i++) {
        arr[i] = Test(i + 3, i + 10);
    }

    for (int i = 0; i < 5; i++) {
        arr[i].print();
    }

    return 0;
}




/*
run:

x = 3 y = 10
x = 4 y = 11
x = 5 y = 12
x = 6 y = 13
x = 7 y = 14

*/

 



answered May 11, 2021 by avibootz
0 votes
#include <iostream>
#include <vector>

class Test {
    int x, y;
public:
    Test() = default;
    Test(int a, int b) : x(a), y(b) {}

    void print() const {
        std::cout << "x = " << x << " y = " << y << "\n";
    }
};
int main(){
    std::vector<Test> array;

     for (int i = 0; i < 5; i++) {
        array.push_back(Test(i + 3, i + 10));
    }

    for (const auto &item : array) {
        item.print();
    }

    return 0;
}




/*
run:

x = 3 y = 10
x = 4 y = 11
x = 5 y = 12
x = 6 y = 13
x = 7 y = 14

*/

 



answered May 11, 2021 by avibootz

Related questions

...