passing character arrays to constructors

Hi! Can you pass an array of characters to a constructor? I keep trying to but it's saying that the variable is unknown.
I'm trying: class expense...
expense::expense(char[]fname);...

Any help is appreciated.
The function should be declared like this:

expense::expense(char fname[]);

and called like this

expense("hello");
Make sure to watch your const correctness. Unless your constructor expects to be able to modify your argument array, you should make it const. That way you can use things like "hello" (a const char array) as argument.
1
2
3
4
5
6
7
8
9
10
11
12
#include <fstream>

class expense
  {
  public:
    expense( const char* fname )
      {
      datafile.open( fname );
      }
  private:
    fstream datafile;
  };


You can also use the <string> library and get much more useful stuff:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <fstream>
#include <string>

class expense
  {
  public:
    expense( const std::string& fname )
      {
      datafile.open( fname.c_str() );
      }
  private:
    fstream datafile;
  };


In both cases, you can call the constructor with a const char array:
1
2
3
4
5
int main()
  {
  expense widgetCosts( "widgets.dat" );

   ...

Hope this helps.
Topic archived. No new replies allowed.