I have a class, ‘Cat’, and a subclass of the Cat class, ‘DerivedCat’. Cat has a function meow(), while DerivedCat overrides this function.
In an application, I declare a Cat object:
Cat* cat;
Later in the application, I initialize the Cat instance:
cat = new DerivedCat();
- Which ‘meow()’ gets called? Why?
- What are the advantages of declaring as the superclass type like this?
- What is an example of where I would want to do this?
Assuming you meant
Cat * cat;, it depends on whether the meow method is virtual or not:DerivedCatwill be used.Catwill be used.In Java all non static methods are virtual by default. This is often what you want. However virtual methods can add a performance overhead at runtime to determine which implementation to call (e.g. a lookup in a vtable). Even if you never create a subclass you may still have to pay for this performance overhead. One of C++’s goals is to produce high performance code and therefore all methods are non-virtual by default.