user451498
user451498

Reputation:

const to non-const c++

is this possible:

changing a constant variable to non-constant

I am making a whole new string class and my constructor looks like this

LString(const char string1[]) {/* whatever I do */}

I wouldn't put the const keyword but that is the only way I can get strings like

LString ls = "a string";

I will have a lot of functions to modify this string

even though I make a copy of this string I still cannot convert const to non const

is it possible

if not, can anyone think of a loophole

ok so some people were saying that there is no problem, well here is my code

#include <iostream>
#include <cstdlib>
using namespace std;
class LString
{
public:
LString(const char string1[]){
char s1[250] = {string1};
cout << "you constructed LString with a const string as a parameter";
}

};

this comes up with the following errors

file.cpp: In constructor 'LString::LString(const char*)':

file.cpp:7:24: error: invalid conversion from 'const char*' to 'char'

if this makes a difference I am using the mingw compiler without an IDE

I am compiling through the command prompt

I think thats all the info you might need

tell me if you need anymore

Upvotes: 5

Views: 3344

Answers (3)

mpen
mpen

Reputation: 282865

I don't see the problem. Keep the constructor signature as it is, but make the internal variable non-const and copy it over. Copy it at the start of the func and then work with that variable instead.

Upvotes: 1

Jay
Jay

Reputation: 14471

I believe the compiler thinks you're trying to change the string you're assigning from. Since it can't be changed that's why it's complaining. Did you make a copy of the string to make changes to?

Upvotes: 2

Alex Brown
Alex Brown

Reputation: 42872

Your constructor is fine - the input should be const.

The copy can be non-const, no problem.

#include <string.h>
class A {
  public:
  A(const char* string)
    : a(strdup(string))
  {}
  char* a;
};

Here I'm using strdup to make a copy. What are you using?

Upvotes: 4

Related Questions