You are here:

C++/constructors

Advertisement


Question
Hi

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

Answer
I 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 ;
}  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.