I have a set of classes like this:
class A {
public:
int DoIt() {
//common code
}
};
class B : public A {
int DoIt() {
if (A::DoIt() == 1) {
return 1;
}
else {
// do b specific code
}
}
};
class C : public A {
int DoIt() {
if(A::DoIt()==1) {
return 1;
}
else {
// do c specific code
}
}
};
Is there a way I can avoid manually putting this code:
if (A::Doit() == 1) { return 1; } else {
in every class which is derived from A?
Static Method Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class.
base (C# Reference) The base keyword is used to access members of the base class from within a derived class: Call a method on the base class that has been overridden by another method.
Using a qualified-id to call a base class' function works irrespectively of what happens to that function in the derived class - it can be hidden, it can be overridden, it can be made private (by using a using-declaration), you're directly accessing the base class' function when using a qualified-id.
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.
Just separate the specific code to another method virtual method.
class A
{
public:
int DoIt() /*final*/
{
// common code
if (return_value == 1)
return 1;
else
return DoIt_specific();
}
private:
virtual int DoIt_specific() = 0;
// ^ or some "A"-specific actions if A cannot be abstract.
};
class B : public A
{
virtual int DoIt_specific() /*override*/
{
// specific code for B
}
};
This is known as the non-virtual interface idiom.
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