Soso Soso wrote:
I know that, but if you look at the code carefully you will see that I
am trying to call base method 'knox' from inside 'test' method. So
parent() will try to call base method of 'test', which is not what I
want.
But the point of overriding in a subclass is to be able to use the same
method name to refer to a derived method. You appear to be working at
cross-purposes -- on the one hand, redefining a method in the child class,
on the other, trying to get around the fact that you have redefined it.
By the way, this works exactly the same way in Java and C++. If you override
a method in the child class, you have to use "super" or some variant
thereof to access the parent's version. Here are examples in C++, Java and
Ruby, all of which emit the same result:
C++:
···
-----------------------------------
#include <iostream>
using namespace std;
class Parent {
public:
void try_this(void) {
cout << "parent" << endl;
}
};
class Child : public Parent {
public:
void try_this(void) {
Parent::try_this();
cout << "child" << endl;
}
};
int main(int argc, char **argv) {
Child ch;
ch.try_this();
return 0;
}
-----------------------------------
Java:
-----------------------------------
class Parent {
void try_this() {
System.out.println("parent");
}
}
public class Parent_Child extends Parent {
void try_this() {
super.try_this();
System.out.println("child");
}
public static void main(String args) {
Parent_Child ch = new Parent_Child();
ch.try_this();
}
};
-----------------------------------
Ruby:
-----------------------------------
#!/usr/bin/ruby -w
class Parent
def try_this()
puts "parent"
end
end
class Child < Parent
def try_this()
super()
puts "child"
end
end
ch = Child.new
ch.try_this()
-----------------------------------
All emit the same result.
--
Paul Lutus
http://www.arachnoid.com