J.g J.g - 1 month ago 8
C++ Question

If my vector doesn't contain a construct how to set it to zero

I get the no default constructor exists for class "vector" Error


#include <iostream>
#include <string>
#include "myVector.h"

using namespace std;

int main()
vector<int> myvecA;
cout << "Vector A size: " << myvecA.size() << endl;

return 0;


#include <iostream>
using namespace std;

template <class V>
class vector{

vector(V x) {
bool(x = 0)
sizearr = 0;
if (x != 0)
return x;
sizearr = x;


V size();


V sizearr;


template <class V>

V vector<V>::size() {
return sizearr;

I don't know how to make it so that if

vector<int> myvecA;

doesn't contain a construct that it will set the construct to 0 so i can return size as 0.

I apologize if my question is not very clear. I'm just look for help so I can learn.I'm not very good at c++.


You just need to provide a default constructor for the class

template <class V> class vector {

 explicit vector(): sizearr(0) {}

Also, constructors do not "return" in the sense used for normal functions. A constructor initializes the internals of a class, the memory needed for the object of the class is created using either new keyword or allocated on the stack.

One more thing, you have to do is to prevent your class from interfering with existing classes (in this case std::vector). The way to do this is to remove that declaration of using namespace std from your header file. Having using namespace std will become a problem if you decide to include your header in a file that uses the standard std::vector in which case your new class will conflict with the already existing one or vice versa.

It is also good practice not to use using namespace X declarative because namespaces safeguard against naming conflicts, and exposing the names in the namespace is in direct conflict with the purpose of a namespace. The only recommended place to use using namespace X is when you are implementing functionality for a given namespace in a "private" .cpp file.

Hope that helps. Ask more questions