-1

I have declared std::vector<Training> _classes; in Training.h as a private variable. I want to first get _noOfClasses from the user and then initialise the vector with that many elements, but I am getting an error:

call of an object of a class type without appropriate operator() or conversion functions to pointer-to-function type

Training::Training() : _noOfClasses(0) {
    std::cout << "Enter the number of class\n";
    std::cin >> _noOfClasses;
    _classes(_noOfClasses); //Error
}

How do I initialize the size of the vector from user input, separately?

Niall
  • 30,036
  • 10
  • 99
  • 142
nSv23
  • 429
  • 6
  • 19
  • 2
    Side note: don't use leading underscores when naming your own symbols: _" Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace."_ (C++ ISO standard, section 17.6.4.3.2). – Michael Jul 27 '16 at 08:06
  • 1
    @Michael member variables are not in the global namespace, so that's fine. – Quentin Jul 27 '16 at 08:09
  • @Michael And it's not followed immediately by an uppercase letter, so would be fine. – songyuanyao Jul 27 '16 at 08:14

3 Answers3

3

_classes(_noOfClasses); is not valid syntax, _classes is not functor and you can't invoke function on it. You could use std::vector::resize() to resize it to contain _noOfClasses elements.

_classes.resize(_noOfClasses); 
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
2

you should use _classes.reserve() or _classes.resize() depending on your need to know about them follow this link :Choice between vector::resize() and vector::reserve()

Community
  • 1
  • 1
sinister
  • 31
  • 1
  • 5
1

I would reverse the order - unless the Training class is an "I/O" class, I would separate the construction of the Training class from any user input. Obtain the number of classes first and then construct the Training instance from the obtained user input.

std::size_t noOfClasses;
std::cout << "Enter the number of class\n";
std::cin >> noOfClasses;
// ...
Training::Training(std::size_t noOfClasses)
: classes_(noOfClasses), noOfClasses_(noOfClasses) {
}

That said, you can factor the I/O out into a function of its own and use the result as the argument (error checking omitted);

std::size_t GetTrainingSize()
{
    std::size_t i;
    std::cout << "Enter the number of class\n";
    std::cin >> i;
    return i;
}

Training::Training() : classes_(GetTrainingSize()) {
    // if needed...
    _noOfClasses = classes_.size();
}

To resize a std::vector after construction, the member resize() method can be used. The OP code would then look like;

Training::Training() : _noOfClasses(0) {
    std::cout << "Enter the number of class\n";
    std::cin >> _noOfClasses;
    _classes.resize(_noOfClasses);
}
Niall
  • 30,036
  • 10
  • 99
  • 142