How to declare a class with a constructior outside of a function C++

106 Views Asked by At

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

There are 1 best solutions below

0
On

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 ...
  }
};