Wrong constructor called

Expectations are this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <limits>
#include <stdexcept>
using std::clog;

namespace{

class FloatValue
{
public:
    FloatValue() : m_amount(0.0f)
    {
        clog << "Creating default floating point value.\n";
    }

    explicit FloatValue(float amount) : m_amount(amount)
    {
        clog << "Creating floating point value with amount " << m_amount <<
            ".\n";

        if(std::numeric_limits<float>::infinity() == m_amount){
            throw std::domain_error("Floating point value cannot be infinite");
        }
    }
private:
    float m_amount;
};
    
} // namespace

int main()
{
    const float INFINITE_VALUE = std::numeric_limits<float>::infinity();
    try{
        FloatValue(INFINITE_VALUE);
    }
    catch (const std::domain_error& error) {
        std::cerr << error.what() << std::endl;
    }

    return 0;
}

should print:
Creating floating point value with amount inf
Floating point value cannot be infinite

However when compiling the code the complier issues a warning like:
TestFloatValue.cpp: In function ‘int main()’:
TestFloatValue.cpp:34: warning: unused variable ‘INFINITE_VALUE’

and during execution, the output is:
Creating default floating point value.

What is needed so the code will behave as expected?
Seems that it is creating a FloatValue object called INFINITE_VALUE in the try scope
Try adding an object name at line 35 or make a function returning an unnamed object
Topic archived. No new replies allowed.