I'm studying the book Agile Software Development by Robert C. Martin. In an example on the Open-Closed Principle I had a problem with the dynamic_cast <>.
the example is as follows:
#include <iostream>
#include <vector>
#include<algorithm>
using namespace std;
class Shape {
public:
virtual void Drow() const = 0;
virtual bool Precedes(const Shape & s) const = 0;
bool operator<(const Shape &s){ return Precedes(s);};
};
template<typename T>
class Lessp {
public:
bool operator()(const T i , const T j) {return (*i) < (*j);}
};
void DrowAllShape(vector<Shape*> &vect){
vector<Shape*> list = vect;
sort(list.begin(),
list.end(),
Lessp<Shape*>());
vector<Shape*>::const_iterator i;
for(i = list.begin(); i != list.end() ;i++){
(*i)->Drow();
}
}
class Square : public Shape{
public :
virtual void Drow() const{};
virtual bool Precedes(const Shape& s) const;
};
class Circle : public Shape{
public :
virtual void Drow() const{};
virtual bool Precedes(const Shape& s) const;
};
bool Circle::Precedes(const Shape& s) const {
if (dynamic_cast<Square*>(s)) // ERROR : 'const Shape' is not a pointer
return true;
else
return false;
}
and i get error in the method Precedes of Circle what is the problem ??
You can use
dynamic_cast
to:const
-correct also).const
-correct also).You can't use it to:
For that reason,
is wrong.
You can use
to resolve the compiler error.
You may use use
dynamic_cast<Square const&>(s)
(cast a reference) but that requires atry
/catch
block.