views:

142

answers:

4

Could you tell me what is wrong with my class constructor? Code:

CVector::CVector (int size_)
{
 if (size_ > 0)
 {
  this->size = size_;
  this->data = new double[size];
  for (int i = 0; i < size; i++)
  { 
   (*this)(i) = i;
  }
 }
 cout << "constructor end" << endl;
 return;
}

Usage example:

tvector = CVector(6);

I get an access violation after "constructor end" output.

Update: Constructor call was incorrect. Using

CVector tvector(6); worked.

+6  A: 

I think you want: this->data[i] = i;

Brian R. Bondy
A: 

I assume that by

(*this)(i) = i;

you actually meant

this->data[i] = i;

Right?

Johann Gerell
Yes, basicallt it is the same. I have implemented operator() to access data[].
Ivan Gromov
@Ivan: There is no operator() in the code you posted. Perhaps you didn't post your entire class?
Bill
+1  A: 

You do not need a return statement at the end of a constructor's body.

Constructors do return a value, but that is a more detailed explanation for another time.

Thomas Matthews
+2  A: 

I'm going to assume you didn't add a copy constructor and the destructor frees some memory that you happened to stomp on with some other code.

MSN
+1. One of the most common errors beginners do.
Nemanja Trifunovic