new operator for arrays

P

Pawel_Iks

Let's consider following class:

class A {
int sth;
public:
A(int s): sth(s) {}
A() {}
~A() {}
}

and when I'd like to create an array with 100 elements of A type I
write:

A* tab=new A[100]

but I'm interested if it is possible to use constructor A(int) instead
of A() with new operator, and if not why?
 
A

asm23

Alf said:
* Pawel_Iks:
Let's consider following class:

class A {
int sth;
public:
A(int s): sth(s) {}
A() {}

Note: here the 'sth' member is uninitialized, with indeterminate value.

Instead you can do e.g.

A(): std(0) {}

or merge that with your one-argument constructor by using a default,

A( int s = 0 ): sth( s ) {}

~A() {}
}

and when I'd like to create an array with 100 elements of A type I
write:

A* tab=new A[100]

but I'm interested if it is possible to use constructor A(int) instead
of A() with new operator, and if not why?

You can't, because that's a feature the core language does not support.
However, std::vector supports specification of a default value. E.g.,

std::vector<A> v( 100, A(42) );

In general, use the standard library container types, or e.g. Boost
container types, instead of using new and delete directly.

It's much safer, and much easier.


Cheers, & hth.,

- Alf
hi, Alf, your answer also helped me to understand why we should specify
a default constructor in some "Container" in C++. Thank you!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top