IntelliSense: a reference of type (not const-qualified) cannot be initialized with a value of type "const char [4]"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Reverse String.cpp : main project file.

#include "stdafx.h"
#include <string>
#include <iostream>

std::string reverse(std::string& s)
{
	std::string result;

	for (unsigned int i = 0; i < s.length(); ++i)
	{
		result += s.at(s.length() - 1 - i);
	}

	return result;
}

int main(array<System::String ^> ^args)
{
	std::cout << reverse("ABC"); // will give CBA
    return 0;
}


My C++ compiler keeps underlining the "ABC" bit in the main block for some reason and I am not quite sure why, does anyone have any ideas?
Your reverse functions is expecting to receive the address of a string, not the string itself.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <string>
#include <iostream>

std::string reverse(std::string& s)
{
	std::string result;

	for (unsigned int i = 0; i < s.length(); ++i)
	{
		result += s.at(s.length() - 1 - i);
	}

	return result;
}

int main(){

	std::string s1 = "ABC";

	std::cout << reverse(s1); // will give CBA
	
	return 0;
}
reverse take a variable of type string
"ABC" is not a string it is a char*
you should write
1
2
std::string s("ABC");
std::cout << reverse(s);
Last edited on
7
8
std::string reverse(const std::string& s)
{

VS is complaining that you are trying to create a non-const object reference from a const object.

If something starts a const, you cannot use non-const iterators over it -- because the point of the const-ness is that you are guaranteeing that the object cannot be changed. If you can suddenly treat it as non-const, where does the guarantee go?


In this specific case, your problem is a little more involved than at first blush.

The std::string class takes as a non-explicit constructor a const char* (a "c-string") -- which means that a thing like "ABC" can be automatically converted into a std::string where one is expected.

That is done, leaving you with a temporary string somewhere. In this case, that means that the temporary string is const -- you cannot change it. (This is a language characteristic -- the idea is that there is no point in modifying the string since it will have no effect -- the temporary is destroyed after the function terminates -- and modifications can have side-effects that adversely affect the compiler's ability to reason about your program.)

However, the function takes a reference to a modifiable (non-const) string. (The technical term is mutable.) Meaning that automatically-created objects are not usable as arguments to the function.


Since you don't change the argument string anyway, just make it a const reference to a string -- and suddenly everything matches up (const is const) and everything is happy.

Hope this helps.
Topic archived. No new replies allowed.