Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concise (yet still expressive) C++ syntax to invoke base class methods

I want to specifically invoke the base class method; what's the most concise way to do this? For example:

class Base
{
public:
  bool operator != (Base&);
};

class Child : public Base
{
public:
  bool operator != (Child& child_)
  {
    if(Base::operator!=(child_))  // Is there a more concise syntax than this?
      return true;

    // ... Some other comparisons that Base does not know about ...

    return false;
  }
};
like image 252
sivabudh Avatar asked Mar 12 '10 17:03

sivabudh


3 Answers

No, that is as concise as it gets. Base::operator!= is the name of the method.

And yes, what you are doing is standard.

However, in your example (unless you have removed some code), you do not need Child::operator!= at all. It does the same thing as Base::operator!= will.

like image 181
Andrew Stein Avatar answered Oct 30 '22 14:10

Andrew Stein


1

if ( *((Base*)this) != child_ ) return true;

2

if ( *(static_cast<Base*>(this)) != child_ ) return true;

3

class Base  
{  
public:  
  bool operator != (Base&);  
  Base       & getBase()       { return *this;}
  Base const & getBase() const { return *this;}
}; 

if ( getBase() != child_ ) return true;
like image 42
Alexey Malistov Avatar answered Oct 30 '22 12:10

Alexey Malistov


What you're doing is the most concise and "standard" way to do it, but some people prefer this:

class SomeBase
{
public:
    bool operator!=(const SomeBaseClass& other);
};

class SomeObject: public SomeBase
{
    typedef SomeBase base;  // Define alias for base class

public:
    bool operator!=(const SomeObject &other)
    {
        // Use alias
        if (base::operator!=(other))
            return true;

        // ...

        return false;
    }
};

The benefits of this method is that it clarifies intention, it gives you a standard abbreviation for what could be a long base-class name, and if your base class changes, you don't have to change every use of the base.

See Using "super" in C++ for additional discussion.

(Personally, I don't care for this, and I don't recommend it, but I think it is one valid answer to the question.)

like image 42
Kristopher Johnson Avatar answered Oct 30 '22 12:10

Kristopher Johnson