|
-
December 15th, 2008, 01:10 AM
#1
noob needs help
hi i am trying to test a copy constructor but when i create an object from my class the compiler tells me that there is no default constructor but there is one !!!! here is my code
#include <iostream>
using namespace std;
class Rollsheet {
public:
Rollsheet (int num) {
numStudents = num;
scores = new int[num];
}
Rollsheet (const Rollsheet &r) {
numStudents= r.numStudents;
scores= new int [numStudents];
for (int i =0; i < numStudents; i++)
scores[i]= r.scores[i];
}
~Rollsheet () {
delete []scores;
}
void setScores (int s[]) {
for (int k=0; k<numStudents; k++)
scores[k] = s[k];
}
const int *getScores () {
return scores;
}
private:
int *scores;
int numStudents;
};
int main(){
Rollsheet listone;
listone.setScores;
return 0;
}
-
December 15th, 2008, 02:01 AM
#2
Re: noob needs help
The default constructor is one that takes no arguments at all.
-
December 15th, 2008, 02:47 AM
#3
Re: noob needs help
Compiler will create a default constructor in case if you dont specified one.
Last edited by unnamed; December 15th, 2008 at 05:44 AM.
-
December 15th, 2008, 02:49 AM
#4
Re: noob needs help
thanks now it crashes after i fill the list
class Rollsheet {
public:
Rollsheet(){
}
Rollsheet (int num) {
numStudents = num;
scores = new int[num];
}
~Rollsheet () {
delete []scores;
}
Rollsheet (const Rollsheet &r) {
numStudents= r.numStudents;
scores= new int [numStudents];
for (int i =0; i < numStudents; i++)
scores[i]= r.scores[i];
}
void setScores (int s[]) {
for (int k=0; k<numStudents; k++)
scores[k] = s[k];
}
const int *getScores () {
return scores;
}
private:
int *scores;
int numStudents;
};
#include <iostream>
using namespace std;
int main(){
int index;
int num;
Rollsheet listone;
int scores[5];
cout <<"enter five scores"<<endl;
for (index=0; index < 5 ;index++){
cin>>num;
listone.setScores(scores);
}
return 0;
};
-
December 15th, 2008, 03:04 AM
#5
Re: noob needs help
Your default constructor is not allocating memory for scores variable.
Last edited by unnamed; December 15th, 2008 at 05:39 AM.
-
December 15th, 2008, 03:50 AM
#6
Re: noob needs help
i allocate mem in the other constructor
the program crashes after i call the setScores function
like so
in main
int main(){
Rollsheet listone(1);
int scores[5]={1,2,3,4,5};
listone.setScores(scores);
listone.getScores();
return 0;
};
-
December 15th, 2008, 04:22 AM
#7
Re: noob needs help
First, please use code tags when posting code. The code you posted is almost unreadable.
Second, there is so much wrong with the class you posted. This one line program will not work with your class:
Code:
int main()
{
Rollsheet r;
}
Do you know why? You are deleting memory that was never allocated in the destructor.
Regards,
Paul McKenzie
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|