How do we call a virtual method from another method in the base class even when the current instance is of a derived-class?
I know we can call Method2 in the Base class from a method in the Derived class by using base.Method2() but what I want to do is calling it from the other virtual method in the Base class. Is it possible?
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main( string[] args )
{
Base b = new Derived( );
b.Method1( );
}
}
public class Base
{
public virtual void Method1()
{
Console.WriteLine("Method1 in Base class.");
this.Method2( ); // I want this line to always call Method2 in Base class, even if the current instance is a Derived object.
// I want 'this' here to always refer to the Base class. Is it possible?
}
public virtual void Method2()
{
Console.WriteLine( "Method2 in Base class." );
}
}
public class Derived : Base
{
public override void Method1()
{
Console.WriteLine( "Method1 in Derived class." );
base.Method1();
}
public override void Method2()
{
Console.WriteLine( "Method2 in Derived class." );
}
}
}
With the above codes, it will output:
Method1 in Derived class.
Method1 in Base class.
Method2 in Derived class.
while what I would expect is:
Method1 in Derived class.
Method1 in Base class.
Method2 in Base class.
When you want to call a specific base class's version of a virtual function, just qualify it with the name of the class you are after, as I did in Example 8-16: p->Base::foo(); This will call the version of foo defined for Base , and not the one defined for whatever subclass of Base p points to.
Virtual functions allow a program to call methods that don't necessarily even exist at the moment the code is compiled. In C++, virtual methods are declared by prepending the virtual keyword to the function's declaration in the base class.
An abstract class is a class that is designed to be specifically used as a base class. An abstract class contains at least one pure virtual function.
No you cannot do that, the purpose of virtual methods is that derived classes can override the implementation and that the implementation is used even when called from base classes.
If that causes problems then the code you need to run should not be in a virtual method.
Obvious solution:
public virtual void Method1()
{
Console.WriteLine("Method1 in Base class.");
this.Method2Private( );
}
private void Method2Private()
{
Console.WriteLine( "Method2 in Base class." );
}
public virtual void Method2()
{
Method2Private();
}
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