I'm having some problems with the const_cast
function. I created a class Calorimeter
that consists of a CaloGrid
and some other stuff. I have to overload the grid()
function to return the CaloGrid
belonging to the class Calorimeter
, however calling the main function returns a segmentation fault.
I know that using const_cast
is not the best practice, but for this assignment I have to use it. Simply duplicating the code for the const CaloGrid& grid() const
for the non-constant function would probably work.
What am I doing wrong? Is there a better way of doing this? And what is the point of overloading the function with a const
copy of the function?
main.cpp
/*headers*/
int main() {
// create 2x2 Calorimeter object
Calorimeter C(2,2);
// return the CaloGrid class from this object
C.grid();
// gives segmentation error
}
Calorimeter.cpp
/*headers*/
// Calorimeter is object with CaloGrid of dimensions nx by ny
Calorimeter::Calorimeter(int nx,int ny){
// initalize the grid and allocate memory
Cgrid = new CaloGrid(nx,ny);
}
Calorimeter::~Calorimeter(){
// delete memory
delete Cgrid;
}
// return the grid
const CaloGrid& Calorimeter::grid() const{
return *Cgrid;
}
// segmentation error
CaloGrid& Calorimeter::grid(){
return const_cast<CaloGrid&> (Calorimeter::grid());
}
Calorimeter.hh
#ifndef CALORIMETER_HH
#define CALORIMETER_HH
class Calorimeter {
public: // Interface
Calorimeter(int,int);
~Calorimeter();
const CaloGrid& grid() const;
CaloGrid& grid();
private: // Implementation
CaloGrid *Cgrid;
}
#endif
Here's your class method:
What does it do? Well:
It calls
Calorimeter::grid()
, and appliesconst_cast
to its return value? What does thisCalorimeter::grid()
do? See above.The issue of what
const_cast
does, and whether or not it's the right thing to do is irrelevant. This class method calls itself, resulting in infinite recursion, and your program blows quickly, as it runs out of its operating system-allotted stack space.Although it's not quite clear what you're trying to do here, the answer as to the reason of your segfault is quite simple: infinite recursion.
The recursive call does not invoke the other, overloaded,
const
class method. This is being called from a mutable class method, so it picks the mutable overload, again.