Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ avoiding manually calling base class function

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?

like image 627
Vivek Goel Avatar asked Mar 13 '12 17:03

Vivek Goel


People also ask

How you call the base class method without creating an instance?

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.

What should be used to call the base class method?

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.

Can we call base class function using derived class object?

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.

How do you call a virtual function 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.


1 Answers

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.

like image 162
kennytm Avatar answered Sep 27 '22 21:09

kennytm