Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling an overridden method from the base class

Tags:

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

like image 833
jamesatha Avatar asked Dec 27 '12 01:12

jamesatha


People also ask

How do you call a base class overridden method?

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. } }

Can you call an overridden method?

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.

How do you access the overridden method of base class from the derived?

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.

How can we call base class method after overriding in C#?

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... }


1 Answers

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.

like image 106
Sergey Kalinichenko Avatar answered Sep 20 '22 03:09

Sergey Kalinichenko