C++/constructors
Expert: vijayan - 9/24/2009
QuestionHi
i have a questions about 'constructors',i actually don't know when should i use them,for example in the code below i defined a constructor and initialized it in 'main':
class GradeBook
{
public:
//...
const static int students = 10;
GradeBook( string, const int [] );
private:
int grades[ students ];
//...
};
GradeBook::GradeBook( string name, const int gradesArray[] )
{
setCourseName( name );
for ( int grade = 0; grade < students; grade++ )
grades[ grade ] = gradesArray[ grade ];
}
//...
int main()
{
int gradesArray[ GradeBook::students ] ={ 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
GradeBook myGradeBook(
"Introduction to C++ Programming", gradesArray );
//...
}
but what if i want to prompt the user to enter some numbers, in this case we can't initialize the constructor like the code i mentioned(int gradesArray[ GradeBook::students ] ={ 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
)
we should get 'gradesArray' by using cin?and then send it to constructor?
or is it right to define a function named for instance 'input' and getting 'grades' without using constructor?
Thanx
Bita
AnswerI would prefer one of:
a. Get 'gradesArray' by using cin. And then send it to constructor.
b. Write a default constructor for GradeBook and overload the stream insertion operator to accept a GradeBook from an input stream:
class GradeBook
{
public:
//...
const static int students = 10;
GradeBook() ;
GradeBook( const std::string&, const int [] );
//...
friend std::istream& operator >> ( std::istream& stm, GradeBook& book ) ;
};
//...
int main()
{
GradeBook myGradeBook ;
std::cin >> myGradeBook ;
}