Next Spaceship

Driving into future...

Calling Non-const Member Functions From Const Member Functions

| Comments

Compare the following two segments of codes. Which do you think is better?

1
2
3
4
5
6
7
8
9
10
11
12
class Array{
private:
       int a[100];
public:
       Array(){}
       int & at(int index){
           return a[index];
       }
       const int & at(int index) const  {
             return const_cast<Array*>(this)->at(index);
       }
};
1
2
3
4
5
6
7
8
9
10
11
12
13
class Array{
private:
       int a[100];
public:
       Array(){}
       const int & at(int index)const {
             return a[index];
       }
       int & at(int index){
           return const_cast<int&>(
                  const_cast<const Array *>(this)->at(index));
       }
};

Comments