Search code examples
c++classoopconstructordefault

When do I need a default constructor?


class Test
{
private :
    int i;
public:
    Test(int m)
    {
      i = m;
    }
    void restart(int k)
    {
        Test(k);
    }
};

However, the compiler (VS17) send me an error saying that "no default constructor exists for class Test", but I don't think I need a default constructor since all functions in this class need a int type argument.


Solution

  • In

    class Test {
    // ...
        void restart(int k)
        {
            Test(k);
        }
    };
    

    the statement Test(k); declares a variable of type Test named k. This variable k is initialized by calling the default constructor which doesn't exist.

    I don't think I need a default constructor since all functions in this class need a int type argument.

    That is neither a reason for nor against a class having/needing a default constructor or not.

    If what you want is to set the value of Test::i inside Test::reset() then just do so:

    class Test
    {
    private:    
        int i;
    
    public:    
        Test(int m) : i{ m }  // you should use initializer lists instead of 
        {}                    // assignments in the constructors body.
    
        void restart(int k) { i = k; }
    };