consider the following code

class A
{
int aa;
public: A():aa(0) {}
}

class B
{
int a;
A obj[10]; ----> how to intialise this array in the B class constructor
}

Thanks & Regards
Vadan

Recommended Answers

All 5 Replies

If you want to initialize aa with something other than 0, here is one way. You don't have to do anything to initilize it with 0 because A's constructor already does that.

class A
{
private:
    int aa;
public:
    A() {aa = 0;}
    set(int x) {aa = x;}

};

class B
{
private:
    A obj[10]:
public:
    B()
    {
        for(int i = 0; i < 10; i++)
            obj[i].set(i);
    }
};

From what i understood, if the default constructor in the class A inititalizes all the parameters, then there is no need to explicitly call the constructor in the Class B, for intiializing the array of objects

>>there is no need to explicitly call the constructor in the Class B,
Actually, that isn't possible anyway. Class constructors are never explicitely called. They are called when the compiler constructs the object.

Some addition:
Regrettably, if class A has no default constructor, you can't declare B::A obj[10]; at all.
For example:

// Modified Ancient Dragon's class
class A
{
private:
    int aa;
public: // No default constructor
    A(int a):aa(a) {}
    set(int x) {aa = x;}
};
class B
{
private:
    A obj[10]: // Alas, can't declare this member...
public:
    B()
    {  // vain hope, too late...
        for(int i = 0; i < 10; i++)
            obj[i].set(i);
    }
};

when line 7 is changed as below it works ok

class A
{
private:
    int aa;
public:
    A(int a = 0){aa = a;} // <<< this is ok now.
    void set(int x) {aa = x;}
};
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.