+ 3

How can use char pointer, in private class and use them, to a string or char in my program pls help if can

6th Sep 2017, 2:35 AM
Pickle_Rick()
Pickle_Rick() - avatar
3 Answers
+ 3
This answer will be used to contrast what the other answer(s) given that state to useĀ std::stringĀ (and those answers are correct -- usestd::string). Let's assume that you could only useĀ char *, you can't for some reason useĀ std::string, and that you are dealing with NULL terminated strings. This is a synopsis of what your implementation would have to do (and please compare this with simply usingĀ std::string): #include <algorithm> #include <cstring> class A { public: // construct empty string A () : str(new char[1]()) {} // construct from non-empty A(const char *s) : str(new char[strlen(s) + 1]) { strcpy(str, s); } // copy construct A(const A& rhs) : str(new char[strlen(rhs.str) + 1]) { strcpy(str, rhs.str); } // destruct ~A() { delete [] str; } // assign A& operator=(const A& rhs) { A temp(rhs); std::swap(str, temp.str); return *this; } // setter void setStr(char * s) { A temp(s); *this = temp; } // getter const char* getStr() { return str; } private: char * str; }; Live Example After adding a couple more constructors and a getter function, this follows theĀ Rule of 3. You see how much code we needed to add just to make the class safely copyable and assignable? That's why usingstd::stringĀ is much more convenient than usingĀ char *when it comes to class members. ForĀ std::stringĀ a single line needs to be changed, compared to adding the copy / assignment (and move, which I didn't show) functions. The bottom line is that in C++ if you want strings, use strings (std::string) and try to keep away from usingĀ char *Ā (unless you have a very compelling reason to be usingĀ char *Ā to represent string data).
6th Sep 2017, 2:51 AM
Atul Agrawal
0
@Atul thank you for time & input
6th Sep 2017, 5:19 AM
Pickle_Rick()
Pickle_Rick() - avatar
0
Let get a basic understanding of object programming. In object programming data can be hidden with object or class you create. Private is method use hide data. Public data the whole program can see data. Example: in a bank people are deal with checks you write or deposit. The bank does not want such employees to know your personal data such as social security number, phone number or address you live. It is private and cannot be accessed by mist employees. The process is called hiding data of clients from most employees. Most can only access public data to do their job!
4th Oct 2019, 6:05 AM
Lloyd L Conley
Lloyd L Conley - avatar