Question

I have to make a class in which, in the constructor, I validate the arguments before creating the instance.

For that I want to make a static member function in the class, which can be used later to validate user input (that's why it needs to be static).

So it looks a bit like this:

//.h
...
public:
    Constructor(const int thing);
    static bool validateThing(int &thing);
...

//.cpp
Class::Constructor (const int &thing):
m_thing = thing;
{
    PRECONDITION(validateThing(thing));
    // the PRECONDITION macro refers to a homemade function that throws an error
    // if the bool in argument is false
}
...

// Later on, in the main file
...
cout << "Enter the thing" << endl;
int thing;
cin >> thing;

cout << "This thing is ";
if (!Class::validateThing(thing))
{
    cout << "not ";
}
cout << "valid." << endl;
...

When I try to build the class, I get the following error message:

no matching function for call to 'Class::validateThing(int &thing)'

What should I understand to make this work?

Was it helpful?

Solution

Make the following changes:

//.h
public:
    Constructor(int thing);
    static bool validateThing(int thing);

//.cpp
Class::Constructor(int thing): m_thing(thing)
{
    PRECONDITION(validateThing(thing));
    //etc.
}

bool Class::validateThing(int thing)
{
    //implement here
}

It appears you did not provide an implementation of validateThing. You should also make sure declarations and definitions agree on types of parameters (const/non-const, references etc.) and initialize members correctly.

Functions like the constructor and validateThing should take const& arguments. But for simple types like int you can also pass by value.

OTHER TIPS

Instead of remove const specifier as suggested by @iavr, just add const in the spec of validateThing function, like this:

//.h
...
public:
    Constructor(const int thing);
    static bool validateThing(const int &thing);
...

And don't forget to implement the validateThing function.

IMO exhaustive use of const specifier is a good design. It's good to know and often very important that some function does not change its argument. It's useful when we using Design by Contract and we have to care about internal and permissible class states.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top