Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector of class without default constructor

Tags:

c++

c++11

vector

Consider the following class:

Class A
{
    public:
       A() = delete;
       A(const int &x)
       :x(x)
       {}
    private:
       int x;
};

How can one create an std::vector<A> and give an argument to the constructor A::A(const int&)?

like image 960
Bojack Avatar asked Apr 28 '15 13:04

Bojack


People also ask

What happens if there is no default constructor?

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .

Can a class have no default constructor?

No default constructor is created for a class that has any constant or reference type members.

Does std::vector require default constructor?

Every time it appears as if std::vector "requires" a default constructor from you, it simply means that somewhere you relied on a default argument of some of the vector s methods, i.e. it was you who tried to default-construct an element, not the vector.

Do you always need a default constructor?

What is the default constructor? Java doesn't require a constructor when we create a class. However, it's important to know what happens under the hood when no constructors are explicitly defined. The compiler automatically provides a public no-argument constructor for any class without constructors.


1 Answers

How can I create a std::vector of type A and give an argument to A's constructor?

std::vector<A> v1(10, 42);  // 10 elements each with value 42
std::vector<A> v2{1,2,3,4}; // 4 elements with different values

How would I add 3 to the vector?

v.emplace_back(3);          // works with any suitable constructor
v.push_back(3);             // requires a non-explicit constructor

The lack of a default constructor only means you can't do operations that need one, like

vector<A> v(10);
v.resize(20);

both of which insert default-constructed elements into the vector.

like image 185
Mike Seymour Avatar answered Sep 20 '22 13:09

Mike Seymour