My question will probably be best explained by an example.
For example, I have 2 classes: A base class and a derived class:
class baseClass
{
public:
baseClass()
{
foo();
}
virtual bool foo() { printf("baseClass"); return false;}
};
class derivedClass : public baseClass
{
public:
bool foo()
{
printf("derivedClass");
return true;
}
};
When I create an instance of derivedClass
, the constructor in baseClass
will be called, and foo()
will be called from it's constructor. The problem is, the baseClass' constructor is calling its own foo()
and no the overridden foo()
that the derived class has overridden. Is there anyway to make the baseClass call the overridden function, not it's own definition of the function?
6. How to access the overridden method of base class from the derived class? Explanation: Scope resolution operator :: can be used to access the base class method even if overridden. To access those, first base class name should be written followed by the scope resolution operator and then the method name.
A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function.
To perform method overriding in C#, you need to use virtual keyword with base class method and override keyword with derived class method.
You should not call a virtual method from a constructor because the object has not yet been fully constructed. Essentially, the derived class doesn't exist yet, so its methods cannot be called.
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