PDA

View Full Version : Simple C++ error: Cannot convert at initialization


Ribbonic Plague
May 12, 2009, 08:17 AM
Hey guys. I have a very simple code that's spewing out an error:



#include <iostream>
#include <string>
#include "NodeWord.h"
using namespace std;

NodeWord::~NodeWord(){

}

NodeWord::NodeWord(string& word){
data = word;
}


int main()
{
NodeWord * n("New Word");
cout << n->data << endl;
return 0;
}



Where my NodeWord.h is simple a header file of the above constructor/destructor, plus:

string data;
All are public.

Now when I try to compile it, it gives me the following error:

error: cannot convert 'const char*' to 'NodeWord*' in initialization


Naturally, without making n a pointer it works, but as a pointer it doesn't work. This might be a very simple error on my part (complete noob at C++) but any help will be very, VERY APPRECIATED!

Cheers!

Libran
May 20, 2009, 06:56 AM
You can't copy one string into another just my using = sign.

I hope this helps and will not produce errors in other places of your program.

Ribbonic Plague
May 20, 2009, 04:44 PM
Er actually you can:
operator= - C++ Reference (http://www.cplusplus.com/reference/string/string/operator=/)

The operator = is already overloaded in the string class, so you can. In C that's illegal, but in C++ it's OK.

It's OK, I've understood the problem. I guess it kind of makes sense that you can't create a new constructor with a pointer because, well, a pointer is a pointer TO an object, not an object itself. So to make my code work instead of this:



NodeWord * n("New Word");
return n;


I use something like:



NodeWord n("New Word");
NodeWord * node = &n;
return node;


It was indeed a noob problem which I should have seen the moment I received the error *facepalm* but I hope others will learn from this!

gurinderc
Oct 4, 2009, 10:16 AM
In short -

NodeWord * n = new NodeWord ("New Word");

does it makes sense where you are wrong?