Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a compilation error on accidental construction?

Given 2 classes:

...
class Grades{
public:
     Grades(int numExams) : _numExams(numExams){
        _grdArr = new double[numExams];
     }
     double GetAverage() const;
     ...
private: // The only data members of the class
     int _numExams;
     double *_grdArr;
};

class Student{
public:
     Student(Grades g) : _g(g){
     }
...
private: // The only data members of the class
     Grades _g;
};
...

And, a short main program:

int main(){
     int n = 5; // number of students
     Grades g(3); // Initial grade for all students
     // ... Initialization of g – assume that it's correct
     Student **s = new Student*[n]; // Assume allocation succeeded
     for (int it = 0 ; it < n ; ++it){
          Grades tempG = g;
          // ... Some modification of tempG – assume that it's correct
          s[it] = new Student(tempG);
     }
// ...
return 0;
}

This code works fine. But by typo mistake the line:

Grades tempG = g;

has changed to:

Grades tempG = n;

and still it passes the compilation. What simple change can i do in the code (the main() code) to get a compilation error by that typo mistake?

like image 264
Sanich Avatar asked Sep 23 '10 11:09

Sanich


1 Answers

This is because Grades has a single argument constructor which acts as a converting constructor. Such a constructor takes an int argument and creates an object of type Grades.

Therefore the compilation is successful.

Make the consructor of 'Grades' explicit

explicit Grades(int numExams);

This will disallow

Grades g = 2;

but allows all of the following

Grades g = Grades(2)  // direct initialization

Grades g = (Grades)2; // cast

Grades g = static_cast<Grades>(2);

Grades g(2);          // direct initialization.
like image 177
Chubsdad Avatar answered Oct 21 '22 19:10

Chubsdad