strings and classes


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: strings and classes

  1. #1
    Join Date
    Mar 2005
    Posts
    3

    strings and classes

    i have a class:
    Code:
    class cls
    {
         private:
         char *var;
         
         public:
         cls(char *par) { var = par; }
    };
    i also have { char nStr[20] } and I've filled it with some text.
    i create "var" of type cls:
    Code:
    cls var(nStr);
    but when i changes the content of nStr, the content of "var" changes as well.
    how can i prevent it? I'm pretty sure it can be done with pointers, I just couldn't find how to do it.
    can anyone help me please?

  2. #2
    Join Date
    Nov 2003
    Posts
    4,118
    It can be done with pointers, but it's really a mess and so why not opt for a cleaner option? Use an embedded std::string object inside cls, instead of the bare char * pointer:

    class cls
    {
    private:

    std::string s;

    };

    You can assign a string using the = operator. When you change one string it doesn't affect any other string because they have private memory buffers.
    Danny Kalev

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center