Error when casting a reference parameter with dynamic_cast in C++

478 Views Asked by At

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 ??

1

There are 1 best solutions below

0
On BEST ANSWER

You can use dynamic_cast to:

  1. cast a pointer to another pointer (needs to be const-correct also).
  2. cast a reference to another reference (needs to be const-correct also).

You can't use it to:

  1. cast a pointer to a rereference, or
  2. cast a reference to a pointer.

For that reason,

dynamic_cast<Square*>(s)

is wrong.

You can use

if ( dynamic_cast<Square const*>(&s) ) 

to resolve the compiler error.

You may use use dynamic_cast<Square const&>(s) (cast a reference) but that requires a try/catch block.

try 
{
    auto x = dynamic_cast<Square const&>(s);
}
catch ( std::bad_cast )
{
    return false;
}

// No exception thrown.
return true;