Short (but still expressive) C ++ syntax for calling base class methods

I want to specifically call a base class method; what is the most concise way to do this? For instance:

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; } }; 
+4
source share
5 answers

No, this is as concise as it turns out. Base::operator!= Is the name of the method.

And yes, what you do is standard.

However, in your example (if you have not deleted any code) you do not need Child::operator!= At all. It does the same as Base::operator!= .

+8
source

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; 
+5
source

What you do is the shortest and β€œstandard” way to do this, 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 advantages of this method are that it clarifies the intent, it gives a standard abbreviation for what might be a long base class name, and if your base class changes, you do not need to change every use of the base.

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

(Personally, I do not care, and I do not recommend this, but I think this is one correct answer to the question.)

+3
source
 if (condition) return true; return false; 

can be reduced to

 return condition; 
+1
source

I would get rid of the if / then control structure and just return the return value of the base class operator, but otherwise what you are doing is fine.

This may be a little more concise: return ((Base&)*this) != child_;

-1
source

Source: https://habr.com/ru/post/1303962/


All Articles