Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ char * initialization in constructor

I'm just curious, I want to know what's going on here:

class Test
{
char * name;
public:
Test(char * c) : name(c){}
};

1) Why won't Test(const char * c) : name(c){} work? Because char * name isn't const? But what about this:

main(){
char * name = "Peter";
}

name is char*, but "Peter" is const char*, right? So how does that initialization work?

2) Test(char * c) : name(c){ c[0] = 'a'; } - this crashes the program. Why?

Sorry for my ignorance.

like image 933
tuks Avatar asked Feb 20 '26 15:02

tuks


1 Answers

Why won't Test(const char * c) : name(c) {} work? Because char * name isn't const?

Correct.

how does this initialization work: char * name = "Peter";

A C++ string literal is of type char const[] (see here, as opposed to just char[] in C, as it didn't have the const keyword1). This assignment is considered deprecated in C++, yet it is still allowed2 for backward compatibility with C.

Test(char * c) : name(c) { c[0] = 'a'; } crashes the program. Why?

What are you passing to Test when initializing it? If you're passing a string literal or an illegal pointer, doing c[0] = 'a' is not allowed.


1 The old version of the C programming language (as described in the K&R book published in 1978) did not include the const keyword. Since then, ANSI C borrowed the idea of const from C++.
2 Valid in C++03, no longer valid in C++11.

like image 64
Eitan T Avatar answered Feb 22 '26 06:02

Eitan T



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!