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