|
-
virtual functions & name hiding
15-22
Write a class with three overloaded virtual functions. Inherit a new class from this and override one of the functions. Create an object of your derived class. Can you call all the base class functions through the derived-class object? Upcast the address of the object to the base. Can you call all three functions through the base? Remove the overridden definition in the derived class. Now can you call all the base class functions through the derived-class object?
Solution:
The answers are; yes, yes, yes! Virtual functions are inherited. Only if you override one will it replace the inherited one. The compiler generates the virtual function table with the most-derived functions that apply to a class, as you would expect. In the example below, if you were to remove the definition of Derived::f( ), then Base::f( ) would be called automatically.
Code:
//: S15:InheritVirtuals.cpp
#include <iostream>
using namespace std;
class Base {
public:
virtual void f() {
cout << "Base::f()\n";
}
virtual void g() {
cout << "Base::g()\n";
}
virtual void h() {
cout << "Base::h()\n";
}
};
class Derived : public Base {
public:
virtual void f() {
cout << "Derived::f()\n";
}
};
int main() {
Derived d;
Base* bp = &d;
bp->f();
bp->g();
bp->h();
}
/* Output:
Derived::f()
Base::g()
Base::h()
*/
///:~
Firstable, I can see that virtual functions in the base class are NOT overloaded in this code. (here are 3 different functions instead)
The next thing, in main, I can see just the calls by upcasting. There's no common calls by derived-class object, like d.f().
Well, if these virt.functions had been overloaded and than one of them overrided(in derived-class), it couldn't be possible to access any of the base class functions through the derived-class object anymore, ok? (because of name hiding)
On the other hand, if I upcast the address of the object to the base, I could access those base functions which are not overrided in derived-class, and for that which is overrided, version from derived class would be called, ok?
Finally, if I remove the overridden definition in the derived class, I can access all the base class functions through the derived-class object, ok?
So, my answers would be no, no, yes;
Correct?
TVM
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks