Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 934639
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T21:02:08+00:00 2026-05-15T21:02:08+00:00

When I create a std::vector of objects, the constructor of these objects is not

  • 0

When I create a std::vector of objects, the constructor of these objects is not always called.

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

struct C {
    int id;
    static int n;
    C() { id = n++; }   // not called
//  C() { id = 3; }     // ok, called
};

int C::n = 0;


int main()
{
    vector<C> vc;

    vc.resize(10);

    cout << "C::n = " << C::n << endl;

    for(int i = 0; i < vc.size(); ++i)
        cout << i << ": " << vc[i].id << endl;  
}

This is the output I get:

C::n = 1
0: 0
1: 0
2: 0
...

This is what I would like:

C::n = 10
0: 0
1: 1
2: 2
...

In this example, am I forced to resize the vector and then initialise its elements “manually”?
Could the reason be that the elements of a vector are not initialised in an ordered way, from the first to the last, and so I cannot obtain a deterministic behaviour?

What I would like to do, is to easily count the number of objects created in a program, in different containers, in different points of the code, and to give a single id to each of them.

Thank’s!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T21:02:09+00:00Added an answer on May 15, 2026 at 9:02 pm

    The reason is that vector::resize inserts copies by calling the automatically provided copy constructor, rather than the constructors you have defined in your example.

    In order to get the output you want, you can define the copy constructor explicitly:

    struct C {
    //....
    C(const C& other) {
        id = n++;
        // copy other data members
    }
    //....
    };
    

    Because of the way vector::resize works though (it has a second optional argument used as a ‘prototype’ for the copies it creates, with a default value in your case of C()), this creates 11 objects in your example (the ‘prototype’ and 10 copies of it).

    Edit (to include some of the good advice in the many comments):

    There are several downsides to this solution worth noting, as well as some options and variants that are likely to yield more maintainable and sensible code.

    • This method does add maintenance costs, and an amount of risk. You have to remember to modify your copy constructor whenever you add or remove members variables of the class. You don’t have to do that if you rely on the default copy constructor. One way to combat this problem is to encapsulate the counter in another class (like this), which is also arguably better OO design, but then of course you also have to keep in mind the many issues that can crop up with multiple inheritance.

    • It can make it harder for other people to understand, because a copy is no longer exactly what most people would expect. Similarly, other code that deals with your classes (including the standard containers) may misbehave. One way to combat this is to define an operator== method for your class (and it may be argued that this is a good idea when overriding the copy constructor even if you don’t use the method), to keep it conceptually ‘sound’ and also as a kind of internal documentation. If your class gets much use, you will likely also end up providing an operator= so that you can maintain the separation of your automatically generated instance id from class member assignments that should take place under this operator. And so on 😉

    • It might disambiguate the whole issue of ‘different id values for copies’ if you have enough control over the program to use dynamically created instances (via new) and use pointers to those inside containers. This does mean you need to ‘initialise elements “manually”‘ to some degree – but it’s not a lot of work to write a function that gives you back a vector full of pointers to new, initialised instances. If you consistently deal with pointers when using standard containers, you won’t have to worry about the standard containers creating any instances ‘under the covers’.

    If you’re aware of all those issues, and believe you can cope with the consequences (which is of course highly dependent on your particular context), then overriding the copy constructor is a viable option. After all, the language feature is there for a reason. Obviously, it is not as simple as it looks, and you should be careful.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 455k
  • Answers 455k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Always check your warning messages. System.Web.Extensions Assembly cannot be resolved May 15, 2026 at 10:13 pm
  • Editorial Team
    Editorial Team added an answer There are two different concepts here - one is "can… May 15, 2026 at 10:13 pm
  • Editorial Team
    Editorial Team added an answer You have to append the constructor arguments to the class… May 15, 2026 at 10:13 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.