0

Say I had two classes

class Bar{
    public:
    Bar()
    ~Bar()
}
class Foo:public Bar{
    Foo()
    ~Foo
}

Now if I wanted to do the following:

int main(){
     Bar * obj = new Foo();
     Foo * obj2 = dynamic_cast<Foo*>(obj);
     return 0;
}

I get an error that I cannot dynamic cast it because it's not polymorphic. I understand that it's because I don't have a virtual keyword anywhere in my base class (in my case a good situation would be in the destructor). But why do I need this virtual keyword to have this sort of true polymorphism? I understand it in the case of if I was trying to call a, say, display function, where the compiler/whatever is going at run time needs to figure out which display to call. But I'm not sure why it's required here. I'd love an explanation.

Thanks

Warbler
  • 71
  • 1
  • 2
  • 9
  • 2
    I suspect you want another answer than "because the language was designed that way"? – Some programmer dude Nov 14 '18 at 06:49
  • 1
    How would you write a function that was **not** dynamically bound? There needs to be a way to distinguish between a polymorphic function and a bog standard, run of the mill, ordinary function that is never overridden. – Galik Nov 14 '18 at 06:50
  • Hah, yes if I could. Usually languages are designed a specific way, right? There's gotta be some reason :P – Warbler Nov 14 '18 at 06:51

1 Answers1

1

The design rationale around C++ is that you don't pay for what you don't use.

dynamic_cast actually requires classes to be polymorphic. I believe this concept exists in the standard.

When classes are polymorphic, each object of that class actually contains additional information about the type of the object (either directly or indirectly). This increases the size of objects. The compiler doesn't automatically insert this information, but instead only does it if you make a member virtual.

See the answers to this question: C++: Why does a struct\class need a virtual method in order to be polymorphic?

Gregory Currie
  • 607
  • 4
  • 14
  • There is no requirement in the standard that polymorphic classes contain additional information about the type of an object (or a virtual function table, or anything else). What you're describing is how compilers typically support polymorphism - but that's because it is a good practical implementation choice in several ways, not because it is is required by the standard, and not because the standard forbids alternative implementation approaches. – Peter Nov 14 '18 at 09:52