Rorschach
Rorschach

Reputation: 764

C++: Initialize array of objects with parameters within another class

I'm trying to create a class that will have array of objects of another class as its member. This "lower" class constructor demands a parameter (no default c-tor), and I'm not sure how to do this.

In .hpp
class ProcessingElement : public sc_core::sc_module
{
public:
    ProcessingElement( sc_core::sc_module_name name );
    sc_core::sc_module_name name;
};

In .cpp
ProcessingElement::ProcessingElement( sc_core::sc_module_name name ) : name(name) {
    //not relevant
}

And "upper" class:

In .hpp
class QuadPE : public sc_core::sc_module
{
public:
    QuadPE( sc_core::sc_module_name name );
    ProcessingElement pe[4];
};

In .cpp
QuadPE::QuadPE( sc_core::sc_module_name name ) : pe[0]("PE0"), pe[1]("PE1"), pe[2]("PE2"), pe[3]("PE3") {
    //non relevant
}

This obviously produces error, but I'm not sure how to fix it. I would like to avoid using vectors, if possible, so some solutions I found on SO that include vectors are not perfect for me.

As a note, sc_core::sc_module_name is a typedef of const char* or something similar, sadly can't look it up right now.

Thank you.

Upvotes: 2

Views: 65

Answers (1)

Just aggregate initialize the array:

QuadPE::QuadPE( sc_core::sc_module_name name ) : pe{"PE0", "PE1", "PE2", "PE3"} {}

While you may not want to use std::vector, I still suggest you give std::array a look. It's an aggregate too, that serves as a thin (zero overhead) wrapper over a c-style array. Nevertheless, it has full value semantics and is a full-featured standard library container. So you may find it less clunky to work with.

Upvotes: 3

Related Questions