0

So I have class that uses conversion operator to int

class Tiny
{
    char v;
    void assign(int i) {if (i&~077) throw Bad_range(); v = i;}
public:
    class Bad_range {};
    Tiny() : v('0') {}
    Tiny(int i) {assign(i);}
    Tiny& operator=(int i) {assign(i); return *this;};

    operator int() const {return v;}
};

My question is, why does my compiler give me an error when I use default constructor in this case:

Tiny x();

Tiny y = x + 4;
cout << y;

but work perfectly fine when:

Tiny x(6);

Tiny y = x + 4;
cout << y;

(prints out 10)

Asphodel
  • 180
  • 1
  • 1
  • 11
  • 1
    `Tiny x();` actually declares a function called `x` that returns a Tiny instead of declaring a local variable. If you want to use the default constructor just write `Tiny x;` – Turtlefight Dec 18 '21 at 03:01
  • np, glad i could help :) It's a very common issue, see e.g. https://stackoverflow.com/questions/22835517/default-constructor-c - Basically whenever it's ambiguous the function declaration wins :) – Turtlefight Dec 18 '21 at 03:07

0 Answers0