View Single Post
Old 07-20-2005, 06:05 PM   #4 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,544
Valmont is on a distinguished road
This is better and should be done:

The header:
Code:
//Implicit conversion and default constructor.
MyClass(const char* = "");
The implementation:
Code:
#include <cstring>

MyClass::MyClass( const char* s )
   : m_pChars( new char[ strlen( s ) + 1 ] )
{
  std::strcpy( m_pChars, s );
}
Don't forget the destructor!

The wrong code:
Code:
MyClass::MyClass() : 
myString[0]='\0';
{}
You may NOT use "=" here. You must use the parenthesis to explicitly denote the initialization in a constructor. Outside the (copy)constructors, you may use "=" to denote initialization indeed.

There is a second major topic here:
Your code (and Redhead's) implies that myString has a fixed size set in as a data member in the header. But this is illegal for arrays UNLESS it is a static member. LEGAL code below:
Code:
#include <cstring>
#include <iostream>

class MyClass
{
public:
  static char myString[5];
};

char  MyClass::myString[5] = "test"; //OR "" to initialize it as empty.

int main()
{
  std::cout<<MyClass::myString<<std::endl;
  std::cin.get();
  return 0;
}
Conclusion
Use my method (the very first example).
__________________

Last edited by Valmont; 07-20-2005 at 06:55 PM.
Valmont is offline   Reply With Quote