开发者

Dynamic memory allocation with default values

开发者 https://www.devze.com 2023-01-02 20:43 出处:网络
class A { private: int m_nValue; public: A() { m_nValue = 0; } A(int nValue) { m_nValue = nValue); ~A() {} } Now in main if i call
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 crea开发者_如何转开发te 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


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.


if i want to define an array of objects

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

std::vector<A> v(5, A(2));


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消