AlexSavAlexandrov
AlexSavAlexandrov

Reputation: 873

C++ Error when adding objects to vector

I'm new with vectors. I'm trying to add objects to a vector. But the program can't compile because I have a problem in the code. But I don't know what is it. The error is:

error C2664: 'void std::vector<_Ty>::push_back(_Ty &&)' : cannot convert parameter 1 from 'Line (void)' to 'Line &&'

The code is:

Line help_line ();
cin >> ln_quan;
vector <Line> figure_line;
for (int i = 0 ; i < ln_quan ; i++)
{
    figure_line.push_back(help_line);
}

The compiler says that the error is at the 6-th line (figure_line.push_back(help_line);).

I gave up trying to find a tutorial explaining how to add objects (I give up easily when doing such things...).

And what does 'Line (void)' and 'Line &&' mean? Is 'Line (void)' the class 'Line'? If so, what does '(void)' mean in this case?

Upvotes: 2

Views: 1320

Answers (3)

Karl Knechtel
Karl Knechtel

Reputation: 61498

Line help_line ();

This does not mean "help_line shall be an instance of Line created with the default constructor". It means "help_line shall be a function, implemented somewhere else, that takes no arguments and returns a Line instance".

The thing you want is spelled Line help_line;, with no parentheses.

So, you get the following error message:

'void std::vector<_Ty>::push_back(_Ty &&)' : cannot convert parameter 1 from 'Line (void)' to 'Line &&'

Line && is the kind of parameter that push_back is expecting. The && doesn't really matter here; it's best thought of, for beginners, as a kind of calling convention. You're still just passing a Line, because that's the kind of thing you collect in a vector of Lines.

Line(void) is "the type of functions that take no arguments and return a Line instance". (void) is another way to write (), for function arguments (it is discouraged in new code, but sometimes needed when interacting with very old C code).

Upvotes: 3

Robᵩ
Robᵩ

Reputation: 168616

You have declared help_line as a function taking no parameters and returning a Line. Is that what you intended?

If so, then you need to invoke the function, like this:

Line help_line();
...
figure_line.push_back(help_line());

If not, and you intended to declare help_line as an object of type Line, you need this:

Line help_line;
...
figure_line.push_back(help_line);

Upvotes: 4

Peter Alexander
Peter Alexander

Reputation: 54270

Line help_line ();

This declares a function, not a Line. Use Line help_line; instead.

See: Most vexing parse: why doesn't A a(()); work?

Upvotes: 6

Related Questions