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&)
?
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() .
No default constructor is created for a class that has any constant or reference type members.
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.
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.
How can I create a
std::vector
of typeA
and give an argument toA
'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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With