M
Markus Dehmann
I get a segfault in the following scenario (I am not really used to
pointers...):
I have a base class Animal and a derived class Dog. Now I construct
two Dogs and store pointers to them in a set<Dog*>. Beforing storing,
the Dog pointers are passed through a function taking Animal pointers
and dynamic_cast'ing them to Dog pointers.
Looks good to me, but it segfaults. Why? Here is my code:
#include <iostream>
#include <stdexcept>
#include <set>
using namespace std;
class Animal {
public:
Animal(const string& theName):name(theName){}
virtual ~Animal(){}
virtual void speak(){
cout << "I do not speak." << endl;
};
const string& name;
const string& getName(){return name;}
};
class Dog : public Animal {
public:
Dog(const string& n):Animal(n){}
virtual ~Dog(){}
virtual void speak(){
cout << "Woof. I am " << getName() << endl;
};
};
class Zoo {
public:
set<Dog*> dogs;
void addAnimal(Animal* a){
Dog* d;
if((d = dynamic_cast<Dog*>(a))){
dogs.insert(d);
}else throw runtime_error("Unknown animal");
}
};
int main(){
Zoo zoo;
Dog d1("Rex");
Dog d2("Rox");
zoo.addAnimal(&d1);
zoo.addAnimal(&d2);
for(set<Dog*>::iterator it = zoo.dogs.begin(); it !=
zoo.dogs.end(); ++it){
(*it)->speak();
}
}
// (I know that zoo::dogs should be private, I just made it public
here to make code shorter)
Thanks for your comments!
Markus
pointers...):
I have a base class Animal and a derived class Dog. Now I construct
two Dogs and store pointers to them in a set<Dog*>. Beforing storing,
the Dog pointers are passed through a function taking Animal pointers
and dynamic_cast'ing them to Dog pointers.
Looks good to me, but it segfaults. Why? Here is my code:
#include <iostream>
#include <stdexcept>
#include <set>
using namespace std;
class Animal {
public:
Animal(const string& theName):name(theName){}
virtual ~Animal(){}
virtual void speak(){
cout << "I do not speak." << endl;
};
const string& name;
const string& getName(){return name;}
};
class Dog : public Animal {
public:
Dog(const string& n):Animal(n){}
virtual ~Dog(){}
virtual void speak(){
cout << "Woof. I am " << getName() << endl;
};
};
class Zoo {
public:
set<Dog*> dogs;
void addAnimal(Animal* a){
Dog* d;
if((d = dynamic_cast<Dog*>(a))){
dogs.insert(d);
}else throw runtime_error("Unknown animal");
}
};
int main(){
Zoo zoo;
Dog d1("Rex");
Dog d2("Rox");
zoo.addAnimal(&d1);
zoo.addAnimal(&d2);
for(set<Dog*>::iterator it = zoo.dogs.begin(); it !=
zoo.dogs.end(); ++it){
(*it)->speak();
}
}
// (I know that zoo::dogs should be private, I just made it public
here to make code shorter)
Thanks for your comments!
Markus