I have a class which parses the Command line arguments and then returns the parsed value to the client class. For parsing, I need to pass argv
to parse function. I would like to pass by reference but from what I know , we never use the '&' symbol when passing arrays. Arrays are not objects that can be passed by reference. Here is my code:
#include <iostream>
#include <fstream>
using namespace std;
class cmdline
{
const char * ifile;
public:
cmdline():ifile(NULL){}
const char * const getFile() const
{
return (ifile);
}
void parse(int argc,const char** argv)
{
//parse and assign value to ifile
// ifile = optarg;
// optarg is value got from long_getopt
}
};
int main(int argc, char ** argv)
{
cmdline CmdLineObj;
CmdLineObj.parse(argc, const_cast<const char**>(argv));
const char * const ifile = CmdLineObj.getFile();
ifstream myfile (ifile);
return 0;
}
1) Is the way argv
is treated, correct?
2) Better way to handle, ifile
?
3) I want to return ifile
as reference, what change should I do, if needed?
My code works the way it is supposed to work, but the reason I came to SO is to "not-just-make-it-work" but do it properly.
Thanks for your help.
EDIT:: After Mehrdad's comment, I edited like this:
class CmdLine
{
const char * ifile;
public:
const char * & getFile() const
{
return (ifile);
}
But I get the error - invalid initialization of reference of type ‘const char*&’ from expression of type ‘const char’