Ask Me Help Desk

Ask Me Help Desk (https://www.askmehelpdesk.com/forum.php)
-   C (https://www.askmehelpdesk.com/forumdisplay.php?f=438)
-   -   Simple C++ error: Cannot convert at initialization (https://www.askmehelpdesk.com/showthread.php?t=352829)

  • May 12, 2009, 08:17 AM
    Ribbonic Plague
    Simple C++ error: Cannot convert at initialization
    Hey guys. I have a very simple code that's spewing out an error:

    Code:

    #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:
    Code:

    string data;
    All are public.

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

    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!
  • May 20, 2009, 06:56 AM
    Libran

    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.
  • May 20, 2009, 04:44 PM
    Ribbonic Plague

    Er actually you can:
    operator= - C++ Reference

    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:

    Code:

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

    I use something like:

    Code:

    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!
  • Oct 4, 2009, 10:16 AM
    gurinderc

    In short -

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

    does it makes sense where you are wrong?

  • All times are GMT -7. The time now is 12:12 PM.