Reputation: 1569
I was looking at oodesign website for interface segregation example
I understood the example and wrote below code in C++,
#include <iostream>
using namespace std;
class IWorkable {
public:
virtual void work() = 0;
};
class IFeedable{
public:
virtual void eat() = 0;
};
// interface segregation principle - good example
class IWorker : public IFeedable, public IWorkable {
};
class Worker : public IWorkable, public IFeedable
{
public:
void work() {
cout << "working" <<endl;
}
void eat() {
cout << "eating in launch break" <<endl;
}
};
class SuperWorker : public IWorkable, public IFeedable{
public:
void work() {
cout << "working much more" << endl;
}
void eat() {
cout << "eating in launch break" <<endl;
}
};
class Robot :public IWorkable{
public:
void work() {
cout << "Robot working" <<endl;
}
};
class Manager {
IWorkable *worker;
public :
void setWorker(IWorkable *w) {
worker = w;
}
void manage() {
worker->work();
}
};
int main()
{
IWorkable * w1 = new Worker();
IWorkable * sw1 = new SuperWorker();
IWorker *w2;
Manager m1;
m1.setWorker(w1);
m1.manage();
//When worker wants he can eat
w2 = dynamic_cast<IWorker*>(w1);
w2->eat();
return 0;
}
When I run above code I get segmentation fault at w2->eat();
My guess is code is casting only pointer of IWorkable
to IWorker
which won't work because IWorkable
doesn't have eat
method.
If so what would be the solution in this case ? Any suggestion/pointer would help.
Note: I am trying it in C++98 however I am open to learn new way in C++11/14/17.
Upvotes: 1
Views: 1402
Reputation: 7828
Your dynamic_cast
is return
ing NULL
since Worker
doesn't inherit IWorker
. By using the inheritance I assume you were going for, this works correctly.
class Worker : public IWorker { /* your same implmenetations */ };
Upvotes: 2
Reputation: 2434
You are accessing the pointer w2
without assigning it. Since a pointer value defaults to an undefined value, there is no guarantee that it points to a valid object. See: https://en.wikipedia.org/wiki/Dangling_pointer#Cause_of_wild_pointers
Upvotes: 1