0

I am trying to create a vector of a class with parametrized constructor.

#include <iostream>
#include <vector>
using namespace std;

struct foo
{
  foo() {
  cout << "default foo constructor " << endl;
  }  
  
  foo(int i)
  {
      cout << "parameterized foo constructor" << endl;
  }
  ~foo() {
    cout << "~foo destructor" << endl;
  }
};

int main()
{
    std::vector<foo> v(3,1);
}

I was expecting that there would be 3 calls to the parameterized foo constructor but instead I get the output as

parameterized foo constructor
~foo destructor
~foo destructor
~foo destructor
~foo destructor

What is happening here ?

How can I use constructor of vector such that objects of class get created with parametrized constructor?

K_TGTK
  • 765
  • 1
  • 8
  • 24
  • 2
    When monitoring constructor/destructor calls, don't forget copy/move constructors too. – Jarod42 Dec 20 '21 at 13:22
  • 1
    somewhat related: https://stackoverflow.com/q/28716209/4117728. Though, be careful, its not quite uptodate for C++11 and beyond – 463035818_is_not_an_ai Dec 20 '21 at 13:33
  • 1
    Note that `foo(int i)` provides an implicit conversion from `int` to `foo`. In `v(3, 1)` the second argument is implicitly converted to `foo` (providing the one line of output) and that instance is copied 3 times to populate the vector (thus 4 instances, 4 destructors). You failed to provide a copy constructor which prints anything, the compiler provides one that is simply going unnoticed. – François Andrieux Dec 20 '21 at 14:20

1 Answers1

2

What is happening here ?

You can add a user defined copy constructor to see what happens in your code:

#include <iostream>
#include <vector>

struct foo {
  foo() { std::cout << "default foo constructor\n"; }    
  foo(int i) { std::cout << "parameterized foo constructor\n"; }
  ~foo() { std::cout << "~foo destructor\n"; }
  foo(const foo&) { std::cout << "copy constructor called\n"; }  // <---
};

int main() {
    std::vector<foo> v(3,1);
}

Output:

parameterized foo constructor
copy constructor called
copy constructor called
copy constructor called
~foo destructor
~foo destructor
~foo destructor
~foo destructor

From cppreference on the std::vector constructor you are calling:

Constructs the container with count copies of elements with value value.

So...

How can I use constructor of vector such that objects of class get created with parametrized constructor?

The elements are created by calling the copy constructor. However, it is only called once, then the vector is filled with copies.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185