Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 550
Joe Tyman Avatar asked Dec 22 '11 04:12

Joe Tyman


People also ask

Can an array be initialized in a constructor?

You can initialize the array variable which is declared inside the class just like any other value, either using constructor or, using the setter method.

How do you initialize an array of objects with a parameterized constructor in Java?

One way to initialize the array of objects is by using the constructors. When you create actual objects, you can assign initial values to each of the objects by passing values to the constructor. You can also have a separate member method in a class that will assign data to the objects.

Which constructor is used for initialising an object through another object?

A copy constructor is a member function that initializes an object using another object of the same class.

Can we initialize object in constructor?

Each class you declare can optionally provide a constructor with parameters that can be used to initialize an object of a class when the object is created. Java requires a constructor call for every object that's created, so this is the ideal point to initialize an object's instance variables.


1 Answers

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.

like image 72
Mark B Avatar answered Oct 22 '22 11:10

Mark B