-
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;
}
-
Re: noob needs help
The default constructor is one that takes no arguments at all.
-
Re: noob needs help
Compiler will create a default constructor in case if you dont specified one.
-
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;
};
-
Re: noob needs help
Your default constructor is not allocating memory for scores variable.
-
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;
};
-
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