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
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
>>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
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
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343