Boost logo

Boost Users :

From: Stephen Torri (storri_at_[hidden])
Date: 2005-04-24 13:46:22


If I have a abstract class with two classes that implement it how can I
make a check that tests for the type of the implementation classes?

For example:

        class Base {
        public:
                virtual void run (){}
                virtual void stop (){}
        };
        
        class Gas_Pedal : public Base {
        public:
                virtual void run (){}
                void set_rate (unsigned int);
        private:
                unsigned int m_rate;
        };
        
        class Brake_Pedal : public Base {
        public:
                virtual void stop (){}
                void set_pressure (unsigned int);
        private:
                unsigned int m_pressure;
        };

When I have a client that receives a Base object I want to be able to
check at run-time. So that if I am expecting a Gas_Pedal object and I
receive something else I can perform some recovery action. The software
I am designing contains an untold number of arrangements of items. Each
item expect a distinctive input type. If it receives something that it
does not know how to handle or need I want to throw an error.

In order to do this I would like to do something like:
        
        void process (Base* sobj)
        {
                if (! (isExpectedType(sobj))
                {
                        throw NotForMeException ();
                }
        
                Brake_Pedal* bp = dynamic_cast<Brake_Pedal>(sobj);
                bp.set_pressure (50);
        }

So perhaps my design is flawed that I am running into this situation. I
am attempting to keep the interface for the Base class simple. The
underlying types could have different data and access methods because
they differ so widely in what they will do. This example was given to
keep things simple.

Stephen


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net