Reputation: 1445
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();
Upvotes: 1
Views: 162
Reputation: 839224
Assuming you meant Cat * cat;
, it depends on whether the meow method is virtual or not:
DerivedCat
will be used.Cat
will 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.
Upvotes: 2
Reputation: 26060
cat
in your code is not a pointer or a reference, thus cat = new DerivedCat();
calls Cat::operator=(DerivedCat*)
on cat
.
For this reason cat.meow()
will call Cat::meow
.
EDIT after OP's comment:
If cat
was a pointer or a reference, you could make it point to your DerivedCat
instance. In this case if you call a virtual Cat
function that DerivedCat
overloads, the version supplied by DerivedCat
is called.
Polymorphism (which is this features you're asked about) is an important thing, it's at the base of Object Oriented Paradigm. It's not so easy to explain it with an example, I'd suggest you to read about it on Wikipedia or on C++Faq for more implementation details.
Upvotes: 1