954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Initialise array of objects in a class

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

vadan
Newbie Poster
16 posts since Jul 2008
Reputation Points: 10
Solved Threads: 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);
    }
};
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

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

vadan
Newbie Poster
16 posts since Jul 2008
Reputation Points: 10
Solved Threads: 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.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

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);
    }
};
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
 

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;}
};
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You