constructor question

J

junw2000

I write a class as below:

class c1 {

public:

c1(): a(2), c[4]('\0') {} //LINE1

private:

int a;
char c[5];
}

But LINE1 can not pass compiling.

I modify it as:
class c1 {

public:

c1(): a(2){
c[4] = '\0'; //LINE1
}

private:

int a;
char c[5];
}

It works. Is there a better way to write the constructor? Thanks.
 
V

Victor Bazarov

I write a class as below:

class c1 {

public:

c1(): a(2), c[4]('\0') {} //LINE1

If you want to default-initialise your array, use the () syntax:

c1(): a(2), c() {}

There is no other option available to you. By doing "c()" you
set all members to zero.
private:

int a;
char c[5];
}

But LINE1 can not pass compiling.

I modify it as:
class c1 {

public:

c1(): a(2){
c[4] = '\0'; //LINE1
}

private:

int a;
char c[5];
}

It works. Is there a better way to write the constructor? Thanks.

See above. Unfortunately you don't have many choices. AFAIK, the
Committee is working on some improvements.

V
 
J

junw2000

But LINE1 can not pass compiling.

I modify it as:
class c1 {

public:

c1(): a(2){
c[4] = '\0'; //LINE1
}

private:

int a;
char c[5];
}

If I only want to initialize the last element of the array c as a NULL
terminator, is there a better way to do it?
 

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
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top