0

I'm still learning about strings, but I'm trying to use them more often. How could I get something like this to work? I'm not even sure where to start (yes, this is an object. I'm also learning about these atm for an assignment)

MyClass::MyClass(string* newName)
{
  if (newName.length() > maxNameLength) //maxNameLength = 50
  {  
     //do stuff
  }
}
Robolisk
  • 1,682
  • 5
  • 22
  • 49

2 Answers2

3

As an alternative to Ed's answer:

If you really want to use a pointer, your constructor should look like this:

MyClass::MyClass(const std::string* const newName)
{
  if (newName!=nullptr && newName->length() > maxNameLength) //maxNameLength = 50
  {  
    //do stuff
  }
}

Not the operator-> to call length(). You can skip one of the const qualifiers if you either need to change the pointer or its content.

Anyway, using references is usually the better alternative.

Anedar
  • 4,235
  • 1
  • 23
  • 41
2

Here is a little explanation as to use

MyClass::MyClass(const std::string& newName)
  1. You do not need a pointer to the string. A reference is better - hence &
  2. Your constructor should not be modifying this string - tell both the compiler and the developer - hence const
  3. Do not pollute your namespace - hence std::
  4. DO NOT USE using std (see 3)
Ed Heal
  • 59,252
  • 17
  • 87
  • 127
  • can you explain exactly this namespace std stuff? I found that I don't always put "std::string str1" just "string str1", is that bad practice? and if so, should I be using a char. As you can imagine, my class has a private data member that is "string name", hence why I'm calling my constructor to change it. – Robolisk Feb 06 '16 at 10:36
  • 1
    If you are able to do `string str1` then somewhere somebody (maybe you) has a line `using std`. This pollutes the namespace as it includes a lot of stuff. See http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice etc – Ed Heal Feb 06 '16 at 10:39