kwikness
kwikness

Reputation: 1445

C++ Declarations

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();
  1. Which 'meow()' gets called? Why?
  2. What are the advantages of declaring as the superclass type like this?
  3. What is an example of where I would want to do this?

Upvotes: 1

Views: 162

Answers (2)

Mark Byers
Mark Byers

Reputation: 839224

Assuming you meant Cat * cat;, it depends on whether the meow method is virtual or not:

  • If it is virtual, the definition in DerivedCat will be used.
  • If it is not virtual, the implementation in 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

peoro
peoro

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

Related Questions