Joe Tyman
Joe Tyman

Reputation: 1417

Initialize array of class objects in constructor of another class

If I have a class:

class A
{
private:
     char z;
     int x;

public:
     A(char inputz, int inputx);
     ~A() {}
}

I want to make an array of A in class B.

class B
{
private:
    A arrayofa[26];

public:
    B();
    ~B() {}
    void updatearray(); // This will fill the array with what is needed.
}


class B
{
    B:B()
    {
        updatearray();
        std::sort( &arrayofa[0], &arrayofa[26], A::descend );
    }
}

How do I explicitly initialize arrayofa in the constructor of B?

Upvotes: 6

Views: 11109

Answers (3)

Sanish
Sanish

Reputation: 1719

First there should be a default constructor for class A, else B() will not compile. It will try to call the default constructor of members of class B before the body of the constructor starts executing.

You can initialize arrayofa like this:

void B::updatearray()
{
    arrayofa[0] = A('A', 10);
    arrayofa[1] = A('B', 20);
    ...
}

It would be better to use std::vector instead of array.

std::vector<A> v(26, A('a', 10)); //initialize all 26 objects with 'a' and 10

Upvotes: 1

Loki Astari
Loki Astari

Reputation: 264351

You can't.

Each element in the array will be initialized by the default constructor (no parameter constructor).

The best alternative is to use a vector.
Here you specify an a value that will be copy constructed into all members of the vector:

class B
{
private:
     std::vector<A> arrayofa;
public:
     B()
        : arrayofa(26, A(5,5))
          // create a vector of 26 elements.
          // Each element will be initialized using the copy constructor
          // and the value A(5,5) will be passed as the parameter.
     {}
     ~B(){}
     void updatearray();//This will fill the array with what is needed
}

Upvotes: 3

Mark B
Mark B

Reputation: 96233

The default constructor will be called automatically (for non-POD). If you need a different constructor you're out of luck, but you can use vector instead which will support what you need.

Upvotes: 3

Related Questions