Use RTTI to get class name from object implementing interface c++ - c++

I have a class AnimalInterface in Animal namespace:
namespace Animal
{
class AnimalInterface
{
public:
AnimalInterface() = default;
virtual ~AnimalInterface() = default;
virtual std::string makeSound() = 0;
};
}
Suppose I have 2 classes implementing from this interface
class Dog : public AnimalInterface
{
public:
Dog() = default;
~Dog() = default;
std::string makeSound()
{
return "Bark";
}
};
class Cat : public AnimalInterface
{
public:
Cat() = default;
~Cat() = default;
std::string makeSound()
{
return "Meow";
}
};
Now I have a class from where I call these functions. I would like to be able to get the class names of the animals from the objects using run time type information.
void AnimalSounds
{
list<unique_ptr<AnimalInterface>> animals;
animals.push_back(make_unique<Dog>());
animals.push_back(make_unique<Cat>());
for (const auto& animal : animals)
{
cout << typeid(animal).name() << " makes sound: " << animal->makeSound() << endl;
}
}
I expect the output to be
Dog makes sound: Bark
Cat makes sound: Meow
Instead, I get the following
class std::unique_ptr<class Animal::AnimalInterface,struct std::default_delete<class Animal::AnimalInterface> > makes sound: Bark
class std::unique_ptr<class Animal::AnimalInterface,struct std::default_delete<class Animal::AnimalInterface> > makes sound: Meow
How do I fix this? Thanks!

You need to dereference the pointer. That way you get the RTTI information from the object that it points to, not the pointer itself:
const auto& animal_ref = *animal;
cout << typeid(animal_ref).name() << " makes sound: " << animal->makeSound() << endl;
3Dog makes sound: Bark
3Cat makes sound: Meow
Note that you will still have to deal with implementation-defined names as described in the comments. You can use your library's demangle function for that:
int status;
const auto& animal_ref = *animal;
const auto name = abi::__cxa_demangle(typeid(animal_ref).name(), 0, 0, &status);
cout << name << " makes sound: " << animal->makeSound() << endl;
Dog makes sound: Bark
Cat makes sound: Meow
Unless this question was asked for a better understanding of RTTI or for debugging purposes, I would still strongly advise you to reconsider your approach. This is nothing that your code should rely on.
(And yes, technically even demangling might not be enough, and the name might change between invocations. In the implementations that I have worked with, this never happened. At the point where we are talking about cats making meow, this is more a technicality than an actual issue.)

I think the unexpected problem you have is that your animals list contains unique_ptr to Animals. Therefore, when you iterate over that list, each animal in the loop is a unique_ptr<Animal>, which is a template with default arguments. To at least fix that problem, dereference the pointer before using typeid:
for (const auto& animal : animals)
{
cout << typeid(*animal).name() << " makes sound: " << animal->makeSound() << endl;
}
However, what you get here is still implementation defined. Read up on RTTI for more information.

1.) animal is a reference to some element from animals. What does animals contain? It contains unique_ptr<AnimalInterface>, so the compiler prints exactly the right thing, just a bit verbose.
2.) typeif(...).name() is not really refelction. In particular it doesn't give you any garantues about the result whatsoever. See also the reference:
No guarantees are given; in particular, the returned string can be identical for several types and change between invocations of the same program.
3.) I can only think of one robust and standard compliant way to achieve what you want to: another virtual function that returns the animal kind. Or some compiler specific extension, but standard C++ doesn't offer any real reflection at the moment.

Related

Which level should I make for this condition method extracted from somewhere?

If I have a method belongs to class A, and the logic I want to extract is most all about public method of class B. Where should I extract this logic into?
A's private method?
reason: it is extracted from A's method.
B's public method?
reason: it describes class B's state.
free function?
reason: it does not need access B's private member.
or it is always depends?
example:
The code need to be refactored:
class Cat
{public:
void eat(const CatFood& cf)
{
if(!cf.expired() && cf.flavor() == CatFood::Flavor::Tuna)
std::cout << "Cat has eaten food." << std::endl;
else
std::cout << "Cat is hungry and still meow meow." << std::endl;
}
}
Version 1: A's private method
class Cat
{public:
void eat(const CatFood& cf)
{
if(can_eat(cf))
std::cout << "Cat has eaten food." << std::endl;
else
std::cout << "Cat is hungry and still meow meow." << std::endl;
}
private:
bool can_eat(const CatFood& cf) const
{
return !cf.expired() && cf.flavor() == CatFood::Flavor::Tuna;
};
}
Version 2: B's public method
Cat Cat
{public:
void eat(const CatFood& cf)
{
if(cf.eatable_with_flavor(CatFood::Flavor::Tuna))
std::cout << "Cat has eaten food." << std::endl;
else
std::cout << "Cat is hungry and still meow meow." << std::endl;
}
}
class Catfood
{
public:
bool eatable_with_flavor(CatFood::Flavor specific_flavor) const
{
return !expired() && flavor() == specific_flavor;
};
bool expired(){...}
}
Version 3: Free function
Cat Cat
{public:
void eat(const CatFood& cf)
{
if(eatable_with_flavor(cf, CatFood::Flavor::Tuna))
std::cout << "Cat has eaten food." << std::endl;
else
std::cout << "Cat is hungry and still meow meow." << std::endl;
}
}
bool eatable_with_flavor(const CatFood& cf, CatFood::Flavor specific_flavor)
{
return !cf.expired() && cf.flavor() == specific_flavor;
};
I always do the version 1, because it happens in the class A, and just simply extract the codes next to original one. And I think the logic I extracted is only describing class B's state, it could be better to put into class B. After that, I observed the code in new method only invoke B's public methods, it could be better to put it into a free function. I was told the only reason make the function to be a member function is you need to access the class's private member, or you should make it to be a free function.
These three version looks has its reasons. Could anyone give me a suggestion or point out where I am wrong.
btw: Should I write a test for this condition method? Because it looks so trivial. But I know it is a good habit to make as many as possible functions under test.
This is a beautiful example of the ever re-occuring question: Composition or inheritance?
Since isEatable is currently only dependent on CatFood it would be the most natural decision to put it into CatFood. However, the really interesting questions (and thus answers) tend to arise when you start asking: Where will I go next? What if you want to add a a Dog and DogFood, possibly inheriting from the same base classes as Cat and CatFood? What if then isEatable might suddenly depend on the Animal that wants to eat it (in my own experience, age, for example, plays a big role in this decision)? After considering these kinds of questions, you can choose the one that observes least coupling and possibly other benefits, or...
You go with your gut on this one, and focus on all the other issues that you will have to face before your code reaches production. :)

Static ctor/dtor observer for arb. C++ classes

I have a series of classes A, B, ... which have many derived classes which are created inside a module I do not wish to change.
Additionally, I have at least one class Z, which has to be informed whenever an object of type A (or derived classes) is created or destroyed. In the future, there may be more classes, Y, X that want to observe different objects.
I am looking for a convenient way to solve this.
At first glance, the problem seemed trivial, but I'm kind of stuck right now.
What I came up with, is two base classes SpawnObserver and SpawnObservable which are supposed to do the job, but I am very unhappy with them for several reasons (see attached simplification of these classes).
When Z is notified, the actual object is either not yet or not anymore existent, due to the order in which base classes are created/destroyed. Although the pointers can be compared when destroying an object (to remove them from some data-structures in Z) this does not work when it is created and it surely does not work when you have multiple inheritance.
If you want to observe only one class, say A, you are always notified of all (A, B, ...).
You have to explicitly if/else through all classes, so you have to know all classes that inherit from SpawnObservable, which is pretty bad.
Here are the classes, which I tried to trim down to the most basic functionality, which you need to know to understand my problem. In a nutshell: You simply inherit from SpawnObservable and the ctor/dtor does the job of notifying the observers (well, at least, this is what I want to have).
#include <list>
#include <iostream>
class SpawnObservable;
class SpawnObserver {
public:
virtual void ctord(SpawnObservable*) = 0;
virtual void dtord(SpawnObservable*) = 0;
};
class SpawnObservable {
public:
static std::list<SpawnObserver*> obs;
SpawnObservable() {
for (std::list<SpawnObserver*>::iterator it = obs.begin(), end = obs.end(); it != end; ++it) {
(*it)->ctord(this);
}
}
~SpawnObservable() {
for (std::list<SpawnObserver*>::iterator it = obs.begin(), end = obs.end(); it != end; ++it) {
(*it)->dtord(this);
}
}
virtual void foo() {} // XXX: very nasty dummy virtual function
};
std::list<SpawnObserver*> SpawnObservable::obs;
struct Dummy {
int i;
Dummy() : i(13) {}
};
class A : public SpawnObservable {
public:
Dummy d;
A() : SpawnObservable() {
d.i = 23;
}
A(int i) : SpawnObservable() {
d.i = i;
}
};
class B : public SpawnObservable {
public:
B() { std::cout << "making B" << std::endl;}
~B() { std::cout << "killing B" << std::endl;}
};
class PrintSO : public SpawnObserver { // <-- Z
void print(std::string prefix, SpawnObservable* so) {
if (dynamic_cast<A*>(so)) {
std::cout << prefix << so << " " << "A: " << (dynamic_cast<A*>(so))->d.i << std::endl;
} else if (dynamic_cast<B*>(so)) {
std::cout << prefix << so << " " << "B: " << std::endl;
} else {
std::cout << prefix << so << " " << "unknown" << std::endl;
}
}
virtual void ctord(SpawnObservable* so) {
print(std::string("[ctord] "),so);
}
virtual void dtord(SpawnObservable* so) {
print(std::string("[dtord] "),so);
}
};
int main(int argc, char** argv) {
PrintSO pso;
A::obs.push_back(&pso);
B* pb;
{
std::cout << "entering scope 1" << std::endl;
A a(33);
A a2(34);
B b;
std::cout << "adresses: " << &a << ", " << &a2 << ", " << &b << std::endl;
std::cout << "leaving scope 1" << std::endl;
}
{
std::cout << "entering scope 1" << std::endl;
A a;
A a2(35);
std::cout << "adresses: " << &a << ", " << &a2 << std::endl;
std::cout << "leaving scope 1" << std::endl;
}
return 1;
}
The output is:
entering scope 1
[ctord] 0x7fff1113c640 unknown
[ctord] 0x7fff1113c650 unknown
[ctord] 0x7fff1113c660 unknown
making B
adresses: 0x7fff1113c640, 0x7fff1113c650, 0x7fff1113c660
leaving scope 1
killing B
[dtord] 0x7fff1113c660 unknown
[dtord] 0x7fff1113c650 unknown
[dtord] 0x7fff1113c640 unknown
entering scope 1
[ctord] 0x7fff1113c650 unknown
[ctord] 0x7fff1113c640 unknown
adresses: 0x7fff1113c650, 0x7fff1113c640
leaving scope 1
[dtord] 0x7fff1113c640 unknown
[dtord] 0x7fff1113c650 unknown
I want to stress, that I am perfectly aware why my solution behaves the way it does. My question is whether you have a better approach of doing this.
EDIT
As an extension to this question (and inspired by the comments below), I'd like to know:
Why do you think this is a terrible approach?
As an additional note: What I an trying to accomplish by this is to install a normal Observer in each and every created object.
EDIT 2
I will accept an answer that solves problem 1 (bold one in the enumeration above) or describes why the whole thing is a very bad idea.
Use the curiously recurring template pattern.
template<typename T> class watcher {
typename std::list<T>::iterator it;
watcher();
~watcher();
void ctord(T*);
void dtord(T*);
};
template<typename T> class Observer {
public:
typedef std::list<T*> ptr_list;
static ptr_list ptrlist;
typedef typename ptr_list::iterator it_type;
it_type it;
typedef std::list<watcher<T>*> watcher_list;
static watcher_list watcherlist;
typedef typename watcher_list::iterator watcher_it_type;
Observer() {
ptrlist.push_back(this);
it_type end = ptrlist.end();
end--;
it = end;
for(watcher_it_type w_it = watcherlist.begin(); w_it != watcherlist.end(); w_it++)
w_it->ctord(this);
}
~Observer() {
ptrlist.erase(it);
for(watcher_it_type w_it = watcherlist.begin(); w_it != watcherlist.end(); w_it++)
w_it->ctord(this);
}
};
class A : public Observer<A> {
};
class B : public Observer<B> {
};
class C : public A, public B, public Observer<C> {
// No virtual inheritance required - all the Observers are a different type.
};
template<typename T> watcher<T>::watcher<T>() {
Observer<T>::watcherlist.push_back(this);
it = watcherlist.end();
it--;
}
template<typename T> watcher<T>::~watcher<T>() {
Observer<T>::watcherlist.erase(it);
}
template<typename T> void watcher<T>::ctord(T* ptr) {
// ptr points to an instance of T that just got constructed
}
template<typename T> void watcher<T>::dtord(T* ptr) {
// ptr points to an instance of T that is just about to get destructed.
}
Not just that, but you can inherit from Observer multiple times using this technique, as two Observer<X> and Observer<Y> are different types and thus doesn't require diamond inheritance or anything like that. Plus, if you need different functionality for Observer<X> and Observer<Y>, you can specialize.
Edit # Comments:
class C DOES inherit from Observer<A> and Observer<B> through A and B, respectively. It doesn't need to know or care whether or not they're being observed. A C instance will end up on all three lists.
As for ctord and dtord, I don't actually see what function they perform. You can obtain a list of any specific type using Observer::ptrlist.
Edit again: Oooooh, I see. Excuse me a moment while I edit some more. Man, this is some of the most hideous code I've ever written. You should seriously consider not needing it. Why not just have the objects that need to be informed about the others do their creation?
Issue 1 isn't easily solved (in fact I think it's impossible to fix). The curiously recurring template idea comes closest to solving it, because the base class encodes the derived type, but you'll have to add a base to every derived class, if you really insist on knowing the derived type when the base is being constructed.
If you don't mind performing your actual operations (other than the bookkeeping, I mean) or examining the list outside the constructor or destructor of each object, you could have it (re)build the minimal list only when the operation is about to be performed. This gives you a chance to use the fully-constructed object, and makes it easier to solve issue 2.
You'd do this by first having a list of objects that have been constructed, but aren't on the 'full' list. And the 'full' list would contain two pointers per constructed object. One is the pointer to the base class, which you'll store from the Observable constructor, possibly multiple times during the construction of a single object. The other is a void *, pointing to the most derived part of the object -- use dynamic_cast<void *> to retrieve this -- and is used to make sure that each object only appears once in the list.
When an object is destroyed, if it has multiple Observable bases, each will try to remove itself from the lists, and when it comes to the full list, only one will succeed -- but that's fine, because each is equally good as an arbitrary base of that object.
Some code follows.
Your full list of objects, iterable in as straightforward a fashion as std::map will allow. (Each void * and each Observable * is unique, but this uses the Observable * as the key, so that it's easy to remove the entry in the Observable destructor.)
typedef std::map<Observable *, void *> AllObjects;
AllObjects allObjects;
And your list of objects that have been constructed, but aren't yet added to allObjects:
std::set<Observable *> recentlyConstructedObjects;
In the Observable constructor, add the new object to the list of pending objects:
recentlyConstructedObjects.insert(this);
In the Observable destructor, remove the object:
// 'this' may not be a valid key, if the object is in 'allObjects'.
recentlyConstructedObjects.erase(this);
// 'this' may not be a valid key, if the object is in 'recentlyConstructedObjects',
// or this object has another Observable base object and that one got used instead.
allObjects.erase(this);
Before you're about to do your thing, update allObjects, if there've been any objects constructed since last time it was updated:
if(!recentlyConstructedObjects.empty()) {
std::map<void *, Observable *> newObjects;
for(std::set<Observable *>::const_iterator it = recentlyConstructedObjects.begin(); it != recentlyConstructedObjects.end(); ++it)
allObjectsRev[dynamic_cast<void *>(*it)] = *it;
for(std::map<void *, Observable *>::const_iterator it = newObjects.begin(); it != newObjects.end(); ++it)
allObjects[it->second] = it->first;
recentlyConstructedObjects.clear();
}
And now you can visit each object the once:
for(std::map<Observable *,void *>::const_iterator it = allObjects.begin(); it != allObjects.end(); ++it) {
// you can dynamic_cast<whatever *>(it->first) to see what type of thing it is
//
// it->second is good as a key, uniquely identifying the object
}
Well... now that I've written all that, I'm not sure whether this solves your problem. It was interesting to consider nonetheless.
(This idea would solve one of the problems with the curiously recurring template, namely that you have lots of base objects per derived object and it's harder to disentangle because of that. (Unfortunately, no solution to the large number of base classes, sorry.) Due to the use of dynamic_cast, of course, it's not much use if you call it during an object's construction, which is of course the advantage of the curiously recurring thing: you know the derived type during the base's construction.
(So, if your'e going with that style of solution, AND you are OK with performing your operations outside the construction/destruction stage, AND you don't mind the (multiple) base classes taking up space, you could perhaps have each base's constructor store some class-specific info -- using typeid, perhaps, or traits -- and merge these together when you build the larger list. This should be straightforward, since you'll know which base objects correspond to the same derived object. Depending on what you're trying to do, this might help you with issue 3.)
Take a look at Signals and Slots especially Boost Signals and Slots

"Interface" like semantics with boost::bind

I wanted to be able to have something like Java's interface semantics with C++. At first, I had used boost::signal to callback explicitly registered member functions for a given event. This worked really well.
But then I decided that some pools of function callbacks were related and it made sense to abstract them and register for all of an instance's related callbacks at once. But what I learned was that the specific nature of boost::bind and/or taking the value of this seemed to make that break. Or perhaps it was just the fact that the add_listener(X &x) method declaration changed the code that boost::bind generated.
I have a very rough understanding why the problem occurred and I think it's probably functioning correctly as per its design. I am curious: what should I have done instead? Surely there's a Right Way to do it.
Here's some example code:
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <iostream>
using namespace std;
struct X;
struct Callback
{
virtual void add_listener(X &x) = 0;
};
struct X
{
X() {}
X(Callback &c) { c.add_listener(*this); }
virtual void go() { cout << "\t'" << __PRETTY_FUNCTION__ << "'" << endl; }
};
struct CallbackReal : public Callback
{
virtual void add_listener(X &x)
{
f = boost::bind<void>(boost::mem_fn(&X::go), x);
}
void go() { f(); }
boost::function<void (void)> f;
};
struct Y : public X
{
Y() {}
Y(Callback &c) { c.add_listener(*this); }
virtual void go() { cout << "\t'" << __PRETTY_FUNCTION__ << "'" << endl; }
};
int main(void)
{
CallbackReal c_x;
CallbackReal c_y;
X x(c_x);
Y y(c_y);
cout << "Should be 'X'" << endl;
boost::bind<void>(boost::mem_fn(&X::go), x)();
cout << "Should be 'Y'" << endl;
boost::bind<void>(boost::mem_fn(&X::go), y)();
cout << "------------------" << endl;
cout << "Should be 'X'" << endl;
c_x.go();
cout << "I wish it were 'Y'" << endl;
c_y.go();
return 0;
}
Okay, I did not describe the problem completely. The title is misleading.
Oh, man. Downvote this one. I obviously haven't described the problem well and I think this ultimately boils down to mostly a syntactical error. :(
boost::bind takes its parameters by value and copies them. That means
f = boost::bind<void>(boost::mem_fn(&X::go), x);
will pass a copy of x, which will slice off the Y piece of it (if it was really a Y to begin with). To get virtual dispatch to work, you need to pass a pointer to boost::bind:
f = boost::bind(&X::go, &x);
(Note that you don't actually need mem_fn, or to explicitly write <void>, since boost::bind and argument deduction take care of those for you.)
Java interfaces don't specifically exist within C++. Closest you can get is pure abstract base classes. This is generally quite close enough.
The rest of your question is unrelated to interfaces. Java uses the Observer pattern for event connection and dispatch. The interface part is only mildly related because observers are required to obey specific interfaces (of course, since otherwise you wouldn't have any idea what to call).
Using boost::bind to create functors is actually an abstraction beyond interfaces and is thus a more generic solution. The observer pattern and functors are put together into signal/slot idiom/patterns implemented in various libraries like boost::signals, boost::signals2, and gtk++. The Qt version is quite different in mechanics but similar in concept.
So, what's this mean to help you understand what, why and where? I'd suggest starting with a search on what the Observer pattern is and try to write a few implementations.

C++ swap problem in inheritance scenario

I want to add swap functionality to two existing C++ classes. One class inherits from the other. I want each classes' instances to only be swappable with instances of the same class. To make it semi-concrete, say I have classes Foo and Bar. Bar inherits from Foo. I define Foo::swap(Foo&) and Bar::swap(Bar&). Bar::swap delegates to Foo::swap. I want Foo::swap to only work on Foo instances and Bar::swap to only work on Bar instances: I can't figure out how to enforce this requirement.
Here's a sample of what's giving me trouble:
#include <algorithm>
#include <iostream>
struct Foo {
int x;
Foo(int x) : x(x) {};
virtual void swap(Foo &other) {
std::cout << __PRETTY_FUNCTION__ << std::endl;
std::swap(this->x, other.x);
};
};
struct Bar : public Foo {
int y;
Bar(int x, int y) : Foo(x), y(y) {};
virtual void swap(Bar &other) {
std::cout << __PRETTY_FUNCTION__ << " ";
Foo::swap(other);
std::swap(this->y, other.y);
};
};
void display(Foo &f1, Foo &f2, Bar &b34, Bar &b56)
{
using namespace std;
cout << "f1: " << f1.x << endl;
cout << "f2: " << f2.x << endl;
cout << "b34: " << b34.x << " " << b34.y << endl;
cout << "b56: " << b56.x << " " << b56.y << endl;
}
int main(int argc, char **argv)
{
{
Foo f1(1), f2(2);
Bar b34(3,4), b56(5,6);
std::cout << std::endl << "Initial values: " << std::endl;
display(f1,f2,b34,b56);
}
{
Foo f1(1), f2(2);
Bar b34(3,4), b56(5,6);
std::cout << std::endl << "After Homogeneous Swap: " << std::endl;
f1.swap(f2); // Desired
b34.swap(b56); // Desired
display(f1,f2,b34,b56);
}
{
Foo f1(1), f2(2);
Bar b34(3,4), b56(5,6);
std::cout << std::endl << "After Heterogeneous Member Swap: " << std::endl;
// b56.swap(f2); // Doesn't compile, excellent
f1.swap(b34); // Want this to not compile, but unsure how
display(f1,f2,b34,b56);
}
return 0;
}
Here's the output:
Initial values:
f1: 1
f2: 2
b34: 3 4
b56: 5 6
After Homogeneous Swap:
virtual void Foo::swap(Foo&)
virtual void Bar::swap(Bar&) virtual void Foo::swap(Foo&)
f1: 2
f2: 1
b34: 5 6
b56: 3 4
After Heterogeneous Member Swap:
virtual void Foo::swap(Foo&)
f1: 3
f2: 2
b34: 1 4
b56: 5 6
You can see in the final output group where f1.swap(b34) "sliced" b34 in a potentially nasty way. I'd like the guilty line to either not compile or blow up at runtime. Because of the inheritance involved, I think I run into the same problem if I use a nonmember or friend swap implementation.
The code is available at codepad if that helps.
This use case arises because I want to add swap to boost::multi_array and boost::multi_array_ref. multi_array inherits from multi_array_ref. It only makes sense to swap multi_arrays with multi_arrays and multi_array_refs with multi_array_refs.
Swap, like assignment and comparison work well with value types and don't work well with bases of class hierarchies.
I've always found it easiest to follow the Scott Meyer's Effective C++ recommendation of not deriving from concrete classes and making only leaf classes concrete. You can then safely implement swap, operator==, etc. as non-virtual functions for leaf nodes only.
While it's possible to have a virtual swap functions the whole point of having virtual base classes is to have dynamic behaviour at runtime so I think you're on to a loser trying to get all incorrect possibilities to fail at compile time.
If you want to go the virtual swap route, then one possible approach is to do something like this.
class Base
{
public:
virtual void Swap(Base& other) = 0;
};
class ConcreteDerived
{
virtual void Swap(Base& other)
{
// might throw bad_cast, in this case desirable
ConcreteDerived& cother = dynamic_cast<ConcreteDerived&>(other);bad_cast
PrivateSwap(cother);
}
void PrivateSwap(ConcreteDerived& other)
{
// swap implementation
}
};
(Somewhat hacky solution)
Add a protected virtual method, isBaseFoo(), make it return true in Foo, and false in Bar, the the swap method for Foo could check it's argument has isBaseFoo()==true.
Evil, and detects the problem only at run-time, but I can't think of anything better, although Charles Bailey's answer might be better, if you allow dynamic_cast<>.
You cannot really do this, but I don't see the point, anyway. It's no worse than slicing on operator= or copy constructors, and you cannot avoid the latter, either. Why should swap be any different?
For the same reason, it's likely not worth it making swap virtual, for the same reason why you don't make operator= virtual.
I think that this case scenario is now addressed by the presence of move semantics in C++11.
I usually use the swap function only to avoid copy duplication in the assignments so it's only used statically, by the derived class that needs to extend the swap function and that knows the static type of its base so there is no need for virtuality (which as it was stated can lead to subtle problems with slicing). In fact I declare the swap function as a protected method in my base to make sure it's not use directly anywhere else.
The most concrete class can then have the final version public if necessary.
What you are actually trying to do is swap instances of classes from a third party inheritance hierarchy. Given that, I'd forget about using swap on the actual classes and add a level of indirection. Using boost::shared_ptr is a good approach; use shared_ptr instances containing whatever class you want, and swap to your heart's content.
In general, solving the problem as you asked it at compile time is hard for all the reasons described by the other answerers.

C++ class identification question

I'll phrase this in the form of an example to make it more clear.
Say I have a vector of animals and I want to go through the array and see if the elements are either dogs or cats?
class Dog: public Animal{/*...*/};
class Cat: public Animal{/*...*/};
int main()
{
vector<Animal*> stuff;
//cramming the dogs and cats in...
for(/*all elements in stuff*/)
//Something to the effect of: if(stuff[i].getClass()==Dog) {/*do something*/}
}
I hope that's sort of clear. I know about typeid, but I don't really have any Dog object to compare it to and I would like to avoid creating a Dog object if I can.
Is there a way to do this? Thanks in advance.
As others has noted, you should neither use the typeid, nor the dynamic_cast operator to get the dynamic type of what your pointer points to. virtual functions were created to avoid this kind of nastiness.
Anyway here is what you do if you really want to do it (note that dereferencing an iterator will give you Animal* . So if you do **it you will get an Animal&):
for(std::vector<Animal*>::iterator it = v.begin(); it != v.end(); ++it) {
if(typeid(**it) == typeid(Dog)) {
// it's a dog
} else if(typeid(**it) == typeid(Cat)) {
// it's a cat
}
}
Note you can apply the typeid operator to types itself too, as shown above. You don't need to create an object for this. Also note the typeid way doesn't work if you pass it a pointer like typeid(*it) . Using it like that will give you just typeid(Animal*) which isn't useful.
Similar, dynamic_cast can be used:
for(std::vector<Animal*>::iterator it = v.begin(); it != v.end(); ++it) {
if(Dog * dog = dynamic_cast<Dog*>(*it)) {
// it's a dog (or inherited from it). use the pointer
} else if(Cat * cat = dynamic_cast<Cat*>(*it)) {
// it's a cat (or inherited from it). use the pointer.
}
}
Note that in both cases, your Animal type should be polymorph. That means it must have or inherited at least one virtual function.
You can use dynamic_cast, as long as the vector contains Animal pointers.
vector <Animal *> stuff;
for(int i=0;i<stuff.size();i++) {
Dog *pDog = dynamic_cast <Dog *> (stuff[i]);
if(pDog) {
// do whatever with the dog
}
Cat *pCat = dynamic_cast <Cat *> (stuff[i]);
if(pCat) {
// and so on
}
}
but you should be aware that this is generally not the best practice. You should try to work with polymorphism, not against it. In other words, try to write a virtual Animal function that Dog and Cat override, and let the compiler automagically call the right one.
(Also, dynamic_cast is relatively slow, so too many of them will hinder performance; whereas a virtual function call is general just a single instruction.)
Are you sure you want to do that? What you're going to do is the exact contrary of polymorphism, and polymorphism is the best thing in object-oriented programming.
Loosely speaking: Don't do something if you animal is a Dog; let the Animal hierarchy know what to do when one of its objects is a Dog! :)
If you really need your application-level to identify Dogs vs non-Dogs, you should avoid using RTTI (dynamic_cast and typeid), and make that knowledge explicit in your class hierarchy.
for (size_t i = 0; i != v.size(); ++i) {
if (v[i]->isDog()) { v->cleanupPoop(); }
}
There are some minor performance benefits, but the primary benefit is exposing the necessary behavior in your class interface to maintenance programmers. RTTI (being as limited as it is) should not be required in order for a class hierarchy to function.
Now, along with what other people have said, it's likely that the isDog() function could be refactored into something that doesn't require knowledge of the entire hierarchy up-front (such as needsPoopCleanup()). Like everyone else said, you're losing the benefits of polymorphism if your application logic conditionally executes based on object type anyhow.
You can use the typeid operator to do this, e.g.
if (typeid(stuff[i].getClass())==typeid(Dog))
This can't catch if it's a derived class of Dog, though. You can use a dynamic_cast for that. However, any use of typeid or dynamic_cast is often indicative of a design flaw. Usually, you don't need to know what your derived types are, and there's probably a better way that involves polymorphism. It's hard to give the right advice without a real example, though.
using virtual functions:
As indicated by others responses, using virtual functions will often actually be sufficient enough, and is the "C++" way of thinking. Here is an example of using virtual functions:
#include<iostream>
#include<vector>
using namespace std;
/////////////
class Animal {
public:
virtual void move() { cout << "animal just moved" << endl; }
};
class Dog : public Animal {
public:
void move() { cout << "dog just moved" << endl; }
};
class Cat : public Animal {
public:
void move() { cout << "cat just moved" << endl; }
};
void doSomethingWithAnimal(Animal *a) {
a->move();
}
/////////////
int main() {
vector<Animal*> vec;
vector<Animal*>::iterator it;
Animal *a = new Animal;
Dog *d = new Dog;
Cat *c = new Cat;
vec.push_back(a);
vec.push_back(d);
vec.push_back(c);
it = vec.begin();
while( it != vec.end() ) {
doSomethingWithAnimal(*it);
it++;
}
return 0;
}
If this will not be sufficient, then others have already posted answers which actually use conditional logic instead of polymerized logic.
The accepted answer is correct, but you should know that there is another option as well that hasn't been mentioned. You could have a virtual function in the Animal class called "type()" which could return an int or a string (or any type that is comparable).
So for example:
class Animal {
/*...*/
public:
virtual std::string type() const { return "animal"; }
};
class Dog: public Animal{
/*...*/
public:
virtual std::string type() const { return "dog"; }
};
class Cat: public Animal{
/*...*/
public:
virtual std::string type() const { return "cat"; }
};
This way you could just do:
if(array[i]->type() == "dog") { }
The type function could return anything (an int unique to each derived type would work too, but strings illustrate it better).
Simply another option.