Stern
Stern

Reputation: 103

C++ invalid conversion from 'const char*' to char*

I am new to C++. I have an exercise about constructor with const char* parameter.

class Book
{
private: 
   char* title;
}
public:
   Book (const char* title)
   {
      this->title = title;
   } 

When I code the constructor like that, I receive error cannot convert const char to char*. I tried using strcpy(this->title, title); then, it run, but I don't get the expected result. Can anyone help me. Thank you very much.

Upvotes: 0

Views: 1057

Answers (2)

paxdiablo
paxdiablo

Reputation: 882536

C++ doesn't let you easily change a const char * into a char * since the latter has no restrictions on how you can change the data behind that pointer.

If you're doing C++, you should be avoiding char * (legacy C) strings as much as possible. By all means take them as parameters if you must, but you should be turning them into C++ strings at the earliest opportunity:

class Book {
private: 
   std::string m_title;
public:
    Book (const char *title) {
        m_title = title;
    }
};

The one thing you don't want to become is a C+ developer, that strange breed that never quite made the leap from C across to the C++ way of thinking :-)


And, actually, if a given book is never expected to change its title, you're better off making it constant and initialising it, rather than assigning to it, something like:

#include <iostream>
#include <string>

class Book {
    public:
    Book (const char* title): m_title(title) {};
    void Dump() { std::cout << m_title << "\n"; }

    private:
    const std::string m_title;
};

int main() {
    Book xyzzy("plugh");
    xyzzy.Dump();
}

Upvotes: 2

john
john

Reputation: 88017

You are doing an exercise, did the course you are following not explain what you are supposed to do?

I would guess that this is an exercise in dynamic memory allocation and what you are expected to do is use strcpy after you have allocated some memory so that you have somewhere to copy the string to. Like this

this->title = new char[strlen(title) + 1];
strcpy(this->title, title);

You need to allocate one extra char because C style strings are terminated with an additional nul byte.

But any C++ programmer who was doing this for real (instead of it being a learning exercise) would use a std::string as paxdiablo says.

Upvotes: 2

Related Questions