const char as class member

M

markww

Hi,

We can do:

class CSomething {
enum {
ITEM0 = 10,
ITEM1 = 20,
ITEM2 = 30
};
};

but can we do something similar with a constant string?

class CSomething {
const char *pString = "APPLE";
};

I want to be able to do something like:

int main()
{
printf("The static string is [%s]", CSomething::pString);

return 0;
}


Thanks
 
V

Victor Bazarov

markww said:
We can do:

class CSomething {
enum {
ITEM0 = 10,
ITEM1 = 20,
ITEM2 = 30
};
};

but can we do something similar with a constant string?

class CSomething {
const char *pString = "APPLE";
};
No.

I want to be able to do something like:

int main()
{
printf("The static string is [%s]", CSomething::pString);

return 0;
}

C strings need to be initialised where they are _defined_.

Also, don't forget the proper access specifier. As written, your
program won't compile also due to 'pString's being *private*.

V
 
M

mlimber

markww said:
Hi,

We can do:

class CSomething {
enum {
ITEM0 = 10,
ITEM1 = 20,
ITEM2 = 30
};
};

but can we do something similar with a constant string?

class CSomething {
const char *pString = "APPLE";

You probably want "const char* const" and you'll need to add to that
"static" and to define it in the cpp file, not the header.

// In A.hpp
struct A
{
static const char* const pString;
};

// In A.cpp
const char* const pString = "apple";
};

I want to be able to do something like:

int main()
{
printf("The static string is [%s]", CSomething::pString);

Prefer iostreams. Printf is not typesafe.
return 0;
}


Thanks

Cheers! --M
 
F

Frederick Gotham

markww posted:

but can we do something similar with a constant string?

class CSomething {
const char *pString = "APPLE";
};


Either:

/* example1.hpp */

class Arb {
char const static *const str;
};


/* example1.cpp */

char const *const Arb::str = "Apple";


Or:

/* example2.hpp */

class Arb {
char const static str[];
};


/* example2.cpp */

char const Arb::str[] = "Apple";
 

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,772
Messages
2,569,593
Members
45,104
Latest member
LesliVqm09
Top