Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a constructor in a function call?

I've been searching awhile for a good explanation of why/why not the following use of the struct constructor as a function argument is legal. Can someone provide one?

// Begin simple illustrative example C++ program    
#include<vector.h>

struct Item  
{  
  Item(double data, const int lead)
  : m_grid(data), m_lead(lead) {}

  double m_grid;
  int m_lead;
};

int main()
{
  double img = 0.0;
  int steps = 5;
  std::vector<Item> images;
  for (int i = 0; i < steps; i++)
  {
    img += 2.0;
    images.push_back(Item(img,i));
  }
  return 0;
}

I was under the impression a constructor has neither a return type nor statement...

like image 948
Evan Avatar asked Mar 10 '11 09:03

Evan


People also ask

Can I call a constructor in a function?

No, you cannot call a constructor from a method. The only place from which you can invoke constructors using “this()” or, “super()” is the first line of another constructor. If you try to invoke constructors explicitly elsewhere, a compile time error will be generated.

Can constructor call other functions?

A constructor can call methods, yes. A method can only call a constructor in the same way anything else can: by creating a new instance. Be aware that if a method constructs a new object of the same type, then calling that method from a constructor may result in an infinite loop...

Is a constructor a function?

A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword. The purpose of a constructor is to create a new object and set values for any existing object properties.

Is constructor a function in C++?

In this tutorial, we will learn about the C++ constructor and its type with the help examples. A constructor is a special type of member function that is called automatically when an object is created.


1 Answers

It's not the constructor or its return value that's passed to push_back. C++ actually uses the constructor to create a nameless temporary object, which exists only for the duration of the function call; typically, on the stack. This is then passed to push_back, and push_back copies its contents into your vector.

like image 85
moonshadow Avatar answered Oct 21 '22 18:10

moonshadow