[   ^ to index...   |   <-- previous   |   next -->   ]

Accessing overridden members

When a subclass declares a public (or protected) field/method with the same name and profile as a superclass field/method, the subclass's field overrides the superclass's field. For example, in the heirarchy on the previous page, the squid() and clam() members of Baleen and Humpback each override their superclasses' members of the same name.

C++ provides a means for you to access (from within a method) members that are "hidden" by overriding declarations:

class Humpback : public Baleen { // ... some stuff, then: int anotherClam() { return Baleen::clam(); } int yetMoreClams() { return Whale::clam(); } };

As you can see, we prefix the method call with the appropriate class name and the :: scope resolution operator. You are permitted to invoke non-direct superclasses.

In general, using superclass naming in this fashion, especially for non-direct superclasses, is a bad idea. It makes code brittle by forcing a dependency on the class heirarchy and the name of a particular superclass. However, there are legitimate uses of this mechanism.

Overriding vs. overloading

Overloading a method or a function signifies the declaration of multiple methods/functions that share a given name. C++ only permits overloading on the number and types of arguments:

int foo(); // 1. int foo(int a); // 2. OK: different profile void foo(); // 3. Illegal: ambiguous with int foo() int foo(double a); // 4. OK: different profile int foo(int a, int b); // 5. OK: different profile int Bar::foo(); // 6. OK: member, not global function void Bar::foo(); // 7. Illegal: ambiguous with int Bar::foo()

At any given call site, C++ must be able to resolve, at compile time, which function or method is being called.

Overloading is a different concept from overriding; don't confuse them.

P.S.: Note that C++ only dispatches dynamically on the type of the object on which the method is invoked). Therefore, the dynamic type of an argument is not taken into consideration when overload resolution is being computed.


Last modified: Mon Jul 24 15:57:32 PDT 2000