jsuke06
jsuke06

Reputation: 145

Trying to make a custom string class and I keep getting C2440 and a E0415 errors

I'm self teaching from a book. I'm using this example from a book to work with a custom string class and and I keep getting

Error (active) E0415 no suitable constructor exists to convert from "const char [15]" to "Stringz" and Error C2440 'initializing': cannot convert from 'const char [15]' to 'Stringz'

please help me understand what's wrong. I've got a pointer to char in the private field. the constructor initializes with whatever was sent from main as an argument, the length of the argument is taken and used to dynamically allocate the appropriate amount of memory, and finally the address is put in *str in the private field. I tried putting. Any input is appreciated

    #include <iostream>
using namespace std;

class Stringz
{
private:
    char* str;
public:

    Stringz(char* s)
    {
        int length = strlen(s);
        str = new char[length + 1];
        strcpy(str, s);
    }
    ~Stringz()
    {
        cout << "deleting.." << endl;
        delete[]str;
    }

    void display()
    {
        cout << str << endl;
    }
};

int main()
{
    
    Stringz s1 = "made a string ";

    s1.display();
    return 0;
}

Upvotes: 2

Views: 126

Answers (2)

Adrian Mole
Adrian Mole

Reputation: 51825

In C++, the char* and const char* types are distinct. Your string literal is a const array of char so it can 'decay' into a const char* but not to a char* (otherwise, a function may try to modify it's contents, which is not allowed).

To get your Stringz from that literal, you need to make the constructor take a const char* argument:

    Stringz(const char* s)
    {
        int length = strlen(s);
        str = new char[length + 1];
        strcpy(str, s);
    }

You can still use this constructor to make a Stringz from a non-const char array, because the complier can safely cast a non-const into a const. (This is, of course, assuming that the constructor doesn't do anything to try to modify the argument it is given - and yours doesn't.)

Upvotes: 4

Alexey S. Larionov
Alexey S. Larionov

Reputation: 7927

  • you would certainly need to store the length of your string as a private field (or you'd need to calculate it every time again)
  • you're accepting char* in the constructor, but string literal has a type const char * which is not suitable where char* is expected

! Wrong part of the initial answer !

= "made a string " is calling an assignment operator (so called operator=) which you didn't write. To call a constructor you use Stringz s1("made a string ") or String s1{"made a string "}, but there are more problems in your code than that:

Upvotes: 1

Related Questions