Thread: string reference

  1. #1
    Registered User
    Join Date
    Sep 2006
    Posts
    1

    string reference

    void main(void) {
    strimg temp = "first" ;
    fun(temp);
    cout << temp ; // should print Second
    }

    void fun (string& str)
    {
    string newString = "Second";
    str = newString ;
    }

    This is a simple C++ program and working fine if fun() and main() are in same class but if I put fun() in different class/namespace then i get Visual C++ debug dialong box compalining of line 1132 of dbgheap.c .

    I thought that assignment operator is defined for string class so when in fun() I write str = newString , str gets its own copy but then str is refrence so I guess it just points to newString so when function returns I get this error . How could I simply avoid this problem

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Post the code that has the problem in [code][/code] tags. Showing the code that works doesn't really help that much. You are correct in thinking that str = newString means that str gets its own copy. Something else is wrong with the code that doesn't work.

  3. #3
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    As is that code will not compile. the function fun is being defined after main where it is used. You need to move the function definition to before main, or declare the function so that the compiler will know what it is when it first tries to access it.

    Code:
    void fun (string&);
    
    int main(void) {
        strimg temp = "first" ;
        fun(temp);
        cout << temp ; // should print Second
    }
    
    void fun (string& str) {
        string newString = "Second";
        str = newString ;
    }
    also note that main returns int. void main() is a big no-no.
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. reference string
    By chocolatecake in forum C Programming
    Replies: 6
    Last Post: 05-14-2009, 06:02 AM
  2. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  3. Compile Error that i dont understand
    By bobthebullet990 in forum C++ Programming
    Replies: 5
    Last Post: 05-05-2006, 09:19 AM
  4. How to: Use OpenGL with Jgrasp
    By Pickels in forum Game Programming
    Replies: 3
    Last Post: 08-30-2005, 10:37 AM
  5. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM