Let's say I have the following classes:
class A { public: virtual void foo() { bar(); } protected: virtual void bar() { // Do stuff } } class B : public A { protected: virtual void bar() { // Do other stuff } }
If I have an instance of B and call the foo method, which bar method would get called? And is this compiler specific?
Thanks
Because you've typed it as a BaseClass instead of an A or a B, the baseclass is the begin point for the method calls. You might try using a generic: public class AnotherObject { public AnotherObject<T>(T someObject) where T : BaseClass { someObject. MyMethod(); //This calls the BaseClass method, unfortunately. } }
But, since you have overridden the parent method how can you still call it? You can use super. method() to force the parent's method to be called.
Access Overridden Function in C++ To access the overridden function of the base class, we use the scope resolution operator :: . We can also access the overridden function by using a pointer of the base class to point to an object of the derived class and then calling the function from that pointer.
class A { virtual void X() { Console. WriteLine("x"); } } class B : A { override void X() { Console. WriteLine("y"); } } class Program { static void Main() { A b = new B(); // Call A.X somehow, not B.X... }
The A::foo
will call B::bar
if you have an instance of B
. It does not matter if the instance is referenced through a pointer or a reference to a base class: regardless of this, B
's version is called; this is what makes polymorphic calls possible. The behavior is not compiler-specific: virtual functions behave this way according to the standard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With