6

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?

2
  • Building objects in a constructor is often a bad idea. What exactly is your goal? Commented Dec 22, 2011 at 4:54
  • What is A::descend? The normal way to sort things in descending order is to define the normal comparison operators for the class, and then use std::greater. Commented Dec 22, 2011 at 5:00

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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
}

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.