0

I have a simple question that I haven't been able to find an answer to.

If I have a class with a constructor, for example,

class Test
{
public:
    Test(int var);
    ~Test();
};

and I want to declare it outside of main, as a static global

For example.

static Test test1;

int main()
{
    return 0;
}

I will get an error: no matching function for call to 'Test::Test()'

If I try to use static Test test1(50); I will get errors: Undefined reference

What is the right way to do this? Do I need to have 2 constructors, one empty and 1 with variable?

Thanks,

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Mich
  • 3,188
  • 4
  • 37
  • 85
  • 1
    It is trying to call the default constructor, which does not exist. You defined a constructor that accepts an integer, so you either need to pass an integer to the constructor or define a constructor without parameters. – Coda17 Jun 08 '15 at 17:50
  • Would a constructor that takes no arguments ever be *useful* in your program? – Ignacio Vazquez-Abrams Jun 08 '15 at 17:50
  • Better for you not knowing: `static Test test(1);` (Please avoid it) –  Jun 08 '15 at 17:51
  • 2
    Linux and windows tags has nothing to do with this question! – XOR-Manik Jun 08 '15 at 17:52
  • 1
    You most probably missed to provide a definition for your constructor function, or to link the file that contains it. – πάντα ῥεῖ Jun 08 '15 at 17:53
  • 1
    Provide defination for the member functions `class Test { public: Test(){} Test(int var){} ~Test(){} }; static Test test1(5); int main() { return 0; }` – Rndp13 Jun 08 '15 at 17:57

1 Answers1

0

Most likely you have to provide an implementation for your class constructors and destructor (even an empty implementation), e.g.:

class Test
{
public:
  Test()  // constructor with no parameters, i.e. default ctor
  {
      // Do something
  }

  Test(int var)
  // or maybe better:
  //
  //   explicit Test(int var)
  {
      // Do something for initialization ...
  }

  // BTW: You may want to make the constructor with one int parameter
  // explicit, to avoid automatic implicit conversions from ints.

  ~Test()
  {
      // Do something for cleanup ...
  }
};
Mr.C64
  • 41,637
  • 14
  • 86
  • 162