Some_Guy
Some_Guy

Reputation: 189

Array of objects inside another class with a constructor

If we have a class with a constructor to be initialized in another class's constructor we do the following,

Class A{
 A(int arg):a(arg);
 int a;
};
Class B{
 B(int arg):A_obj(arg);
 A A_obj;
}

I have encountered a situation like the following,

Class B{
 B(int arg1,int arg2);
 A *A_obj//Array of objects of A of size arg2;
}

Apart from initializing this in a serparate function, is there any way this can be done using the constructor initializer?? Also are there any other elegant ways in which this can be handeled.

Thanks!

Edit: I was hoping for some kind of loop functionality within B's constructor initializer.

Edit: Cory's Answer sorts this out. I was wondering if we could further pass an iterating value as an input argument to every instance of A in the A_obj array.

class A{
 A(int arg,std::string n);
 int a;
 std::string name;
}

Something on the lines of A_obj(arg2,A(arg1,"Name"+str(iterator))

Solution (Thanks to Cory)

#include <iostream>
#include<string>
#include <vector>

class A{
public:
    A(int arg,std::string n):a(arg),name(n){};
    int a;
    std::string name;
    void sayhi(){std::cout<<"Hi from "<<name<<std::endl;}
};

class B{
public:
    B(int arg1, int arg2){
        A_obj.reserve(arg2);
        for (std::size_t i = 0; i < arg2; ++i){
            A_obj.emplace_back(arg1, "Name" + std::to_string(i));  // create new A object and add to vector
        }
    }std::vector<A> A_obj;
};

int main(){
    B B_obj(1,10);
    for(int i=0;i<10;i++){
        B_obj.A_obj[i].sayhi();
    }
    return 0;
}

Upvotes: 1

Views: 170

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117876

I would suggest changing your raw array to a std::vector

class B{
 B(int arg1,int arg2);
 std::vector<A> A_obj;
};

Then you can use the member initialization list

B::B(int arg1, int arg2) : A_obj(arg2) {}

This will size your vector with arg2 number of default-initialized A objects.

If you want each A to be initialized with arg1 then you use the other vector constructor

B::B(int arg1, int arg2) : A_obj(arg2, A(arg1)) {}

To pass different values to each object, you'd need to do that in the constructor body

B::B(int arg1, int arg2)
{
    A_obj.reserve(arg2);
    for (std::size_t i = 0; i < arg2; ++i)
    {
        A_obj.emplace_back(arg1, "Name" + std::to_string(i));  // create new A object and add to vector
    }
}

Upvotes: 2

Related Questions