0
class A
{
private:
int m_nValue;
public:
A()
{
m_nValue = 0;
}
A(int nValue)
{
m_nValue = nValue);
~A()
{}
}

Now in main if i call

A a(2);// 2 will be assigned for m_nValue of object A.

Now how do we do this if i want to define an array of objects. Also how do we do this if i dynamically create objects using operator new like

A *pA;
pA = new A[5];// while creating the object i want the parameterised constructor to be 

//called

I hope the question is clear. Do let me know if more explanation is needed

ckv
  • 10,539
  • 20
  • 100
  • 144
  • More "curiosity"? Or more not being prepared to read a c++ textbook? –  Jun 10 '10 at 17:19
  • 2
    So which C++ textbook are you using in which this issue is not covered? –  Jun 10 '10 at 17:23
  • [The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – fredoverflow Jun 10 '10 at 18:32

4 Answers4

5

You cannot do this.

If you want to dynamically allocate an array, it has to be a default-constructable object. This means, it needs to have a constructor with no parameters, which is the one that will be used.

Pavel Radzivilovsky
  • 18,794
  • 5
  • 57
  • 67
  • Not true. It would be true for arrays allocated with new-expressions, but not for arrays in general. An array of non-default-constructible objects can easily be declared with aggregate initializer. – AnT stands with Russia Jun 10 '10 at 18:39
2

if i want to define an array of objects

This is C++, you don't want arrays ;-)

std::vector<A> v(5, A(2));
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
1

You normally can't do this, as array objects are default constructed, but one quick hack is you can create a subclass whose default constructor passes on the parameter(s) you want to the base class.

template<int I>
class B : public A
{
public:
     B() : A(I) { }
};
...

A *pA;
pA = new B<42>[5];

Abusing inheritance in such a fashion is frowned upon in some circles, however.

Terry Mahaffey
  • 11,775
  • 1
  • 35
  • 44
1

If you want to define an array, you can use the aggregate initializer

A a[5] = { 1, 2, 3, 4, 5 };

Note though that aggregate initialization follows copy-initialization semantics, so for each element it will be equivalent to

A a1 = 1;

not to your original

A a1(1);

As for the new-expression... The only initializer you can supply in the array new-expression is the empty () initializer, which triggers value-initialization. No other initializers are supported by the language at this time.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765