-1

I tries the below code, but I'm getting infinite loop that is infinite number of values in the output may I know the reason and what my mistake is: I'm getting the values to enter but after entering I'm getting infinite number of zeroes may the problem be solved: the below one is the code:

   #include<iostream>
   class Vector
   {
       int n,*a,i;
       public:
       Vector()
       {
           int n;
           int *a;
       }
       Vector(int n)
       {
           a=new int[n];
           std::cout<<"Enter array elements "<<std::endl;
           for(i=0;i<n;i++)
           {
               std::cin>>a[i];
           }
           std::cout<<"the elements od the vector are: "<<std::endl;
           for(i=0;i<n;i++)
           {
               std::cout<<a[i]<<std::endl;
           }
       }
       Vector(Vector &v)
       {
           a=v.a;
           std::cout<<"using Copy Constructor elements are:"<<std::endl;
           for(i=0;i<n;i++)
           {
               std::cout<<a[i]<<std::endl;
           }
       }
       Vector& operator=(const Vector& v)
       {
           int n=v.n;
           a=v.a;
           std::cout<<"after assigning values are:"<<std::endl;
           for(i=0;i<n;i++)
           {
               std::cout<<a[i]<<std::endl;
           }
           delete []a;
           return *this;
       }
       ~Vector()
       {
           std::cout<<"Destructor called"<<std::endl;
       }
   };

   int main()
   {
       Vector v1(4);
       Vector v2(v1);
       Vector v3;
       v3=v1;
   }
Bhavana
  • 13
  • 3
  • Your copy constructor and assignment operator are broken. What you have there does not take care of properly copying `Vector` objects. You also failed to deallocate the memory in the `Vector` destructor. – PaulMcKenzie Oct 08 '20 at 15:46
  • Please go through some C++ books. You have used the Constructors incorrect way. Like defining variables, other than memory allocation code etc. Find some good read: https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Build Succeeded Oct 08 '20 at 15:50
  • thankyou for your explaination – Bhavana Oct 09 '20 at 04:23

1 Answers1

1

Your Vector constructor is not updating the member n at all, so it's uninitialized when used, for example, in the copy constructor.

You need to do something like this:

Vector(int n) : n(n) {
  // ...
}

Also, your copy constructor, and assignment operator are incorrect. In both cases, you are not allocating memory for the a pointer, and even if you did, in you're deleting a in your assignment operator before returning.


Also, your default constructor does nothing useful:

Vector()
       {
           int n;
           int *a;
       }

You can just remove it, or do Vector() = default if that's suitable for you. In that case, you should initialize a and n inside the class.

cigien
  • 57,834
  • 11
  • 73
  • 112