0

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

3
Contributors
5
Replies
8
Views
9 Years
Discussion Span
Last Post by Ancient Dragon
0

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);
    }
};
0

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

0

>>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.

0

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);
    }
};
0

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;}
};
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.