-1

Is there a way to assign a class member from a command line argument so that ALL objects of that class have that value (by default)? I want it by default because a member function creates a new object in the Foo class, and I don't want to make Var a function parameter. I want to avoid global variables if possible. I want my code to do what the code below does, but without the use of global variables.

Foo.h:

#include <string>
#include <iostream>

extern int Var;

class Foo{
    public:
         int var;
         Foo();

};

Foo.cpp:

#include "Foo.h"
Foo::Foo(){
    var = Var;
}

main.cpp:

#include "Foo.h"

int Var; // global variable
using namespace std;

int main(int argc, char *argv[]){
    Var = stoi(argv[1]);
    Foo foo;
    cout << foo.var << endl; // should print the command-line argument

}
asrjarratt
  • 314
  • 6
  • 17
  • 1
    What's the problem with receiving the value as constructor parameter: `Foo(int Var) : var(Var) {}` – NetVipeC Feb 10 '15 at 22:16
  • 2
    Use a private class static member and public class static establishment-function. – WhozCraig Feb 10 '15 at 22:16
  • @NetVipeC I edited my OP to clarify. (I want it by default because a member function creates a new object in the Foo class, and I don't want to make Var a function parameter.) – asrjarratt Feb 10 '15 at 22:20
  • In C++11, you could create a lambda in main that capture by value the default and call the member function to create the new F and set later the default. – NetVipeC Feb 10 '15 at 22:23
  • @awilds I can't spot any instantiation of `Foo` in your sample code? What are you acually bothering about? – πάντα ῥεῖ Feb 10 '15 at 22:25
  • better use `stoi`, unless you want a conversion error to go unnoticed – Cheers and hth. - Alf Feb 10 '15 at 22:28
  • 3
    are you familiar with `static` data members? or Meyers' singleton? you don't have to use global variables in order to share a variable between instances. – Cheers and hth. - Alf Feb 10 '15 at 22:29
  • @Cheersandhth.-Alf Thanks everyone for your responses. I wasn't familiar with static data members, but I am now! That was exactly what I was looking for. – asrjarratt Feb 10 '15 at 23:13

1 Answers1

0

I suggest using std::istringstream:

int main(int arg_count, char * * arguments)
{
  std::istringstream arg_stream(arguments[1]);
  unsigned int value;
  arg_stream >> value;
  return 0;
}
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154