Food for thoughts -- polymorphisms in C++

Just a famous interview question.. What are the different ways you could iplemet polymorphism in c++??


All i know is
1. Through Interfaces
2. Templates

To a certain extent function overloading

Anything else that comes to ur mind guys??
Last edited on
Through function pointers.
Anything else guys???
Unions. Generic pointers.

EDIT: Are you sure the question isn't "how would you implement polymorphism in C"?
Last edited on
Well, Could be.. but just thinking about all the ways to exploit polymorphism in C++...

How is that you could implement polymorphism with unions??

What are generic pointerS?? ex please..
I think we're really discussing how polymorphism the 'general concept' can be achieved using C++ rather than the just the specific 'polymorphic' language facilities designed into C++.
Ok.. So how do we exploit polymorphism using unions??

Galik.. We could even discuss from that side.. Y don you post what you think?
Ok.. So how do we exploit polymorphism using unions??
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <typeinfo>
using namespace std;
class Base{
public:
  virtual void see() const{
    cout<<typeid(pointee.d).name()<<endl;
  }
protected:
  union {
    int* d;
    char* p;
  }pointee;
};

class Der:public Base{
public:
  virtual void see() const{
    cout<<typeid(pointee.p).name()<<endl;
  }
};

int main(int argc, char* argv[]){
  const Base& b=Der();
  b.see();
}


I came up with this snip code to show the concept of using union with polymorphism. there could be practical application by using union because it saves space.
Last edited on
Ok.. So how do we exploit polymorphism using unions??


The real question is not how, but why. Why exactly would I want to use a union
to implement polymorphism when the language intrinsically supports it with inheritance
and virtual functions.

If asked how to exploit polymorphism using unions during a job interview, the
right answer is to walk out and find a different job. The concept is stupid.
I guess helios has become busy..!! Hope he ll give us the explanation.. maybe he had someother idea in his mind when he cited unions as a tool for polymorphism...

@everid
Thanks for your idea. But again here we use virtual functions as the tool of polymorphism and we use unions for efficiency..
Topic archived. No new replies allowed.