12

How can I make pure virtual function a operator+(); function. wheh ı do like this in base class int operator+()=0; compiler gives error . in derive class operator+() function compiler say that derive class cannot make . because following class is abstract I know that I cannot create object of abstract classes but now I try to make derive class object.

Here is the code

#include <iostream>
using namespace std;
class ana {
    protected :
    int x;

    public :
    virtual int operator+()=0;
    virtual void operator=(ana&)=0;
    };

class baba : public ana{
    public:
    baba(int k){x=k;}
    int   operator+(baba &ali){
        int k;
        k=x+ali.x;
        return k;
    }
   void operator=(baba &ali){
       x=ali.x;
       }


    };

int main(){
    baba k(4);

    return 0;
    }
Troubadour
  • 13,334
  • 2
  • 38
  • 57
hasan
  • 127
  • 1
  • 1
  • 4
  • 3
    Please show us the code. – Timo Geusch Jun 03 '10 at 21:41
  • 1
    It is rather unlikely that you have found a sensible design involving operators implemented as virtual member functions. I've never seen such beasts. What do you want to achieve doing that? – sbi Jun 03 '10 at 21:43
  • In addition to @sbi, operators are pretty much only for pretty syntax. If you are using virtual functions all your action has to go through pointers anyway, so your code will probably be *uglier* with operators. I suspect, in fact, that you'll have to explicitly call `operator+` like `(&myobj)->operator+(x)` – kibibu Jun 03 '10 at 21:46
  • 7
    To whoever upvoted this - in what sense is this a good question? –  Jun 03 '10 at 21:52
  • 3
    @Neil Butterworth: After Troubadour posted the "code" from the "answer" below, I upvoted from -1 to 0. Not sure it deserves to go higher, but I didn't think that with this part resolved it deserved a negative score. I expect if somebody disagrees, they'll vote it back down again. – andand Jun 04 '10 at 02:05
  • @sbi Unless I am mistaken, there are some valid use cases for this. My current use case is an interface for a PID regulator. The error is calculated by subtracting a `current state` from `target state`. To make this work for `any kind` state (vehicle, stationary robot, light bulb, whatever), I `could` use an interface called `State` with a virtual `- operator` and its derivatives take the responsibility of providing the exact implementation – Sam Hammamy Apr 18 '19 at 02:44
  • 1
    @SamHammamy: I find the idea of subtracting states dubious. What does it even mean to subtract `initial_state` from `error_state`? It certainly seems to violate the first of [my basic rules for operator overloading](https://stackoverflow.com/a/4421708/140719). – sbi Jun 06 '19 at 09:26

6 Answers6

13

Your vague mentions of code are essentially impossible to follow. Answering your question "How can I make pure virtual function a operator+(); function", there's absolutely no secret to it, e.g. consider the following trivial program:

#include <iostream>

class base {
public:
  virtual int operator+(int) const = 0;
};

class deriv: public base {
public:
  int operator+(int) const {return 23;}
};

int main() {
  deriv d;
  base& b = d;
  std::cout << b + 15 << std::endl;
  return 0;
}

This compiles and runs just fine and emits 23 as expected. Whatever it is that you're doing wrong, obviously it must therefore be different from this (and probably not connected to the specific issue of having an operator overload be pure virtual).

Edit: (as per comments, added const to the method just in case you want to call it w/a const base& -- note that other answers have also omitted this const; and, also per comments):

If you want to be able to also do 15 + b, just add a free-standing function for that very purpose, say just before main:

inline int operator+(int i, const base&b) {
    return b + i;
}
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • 2
    This has the obvious disadvantage that `15 + b` will not work. –  Jun 03 '10 at 21:50
  • 2
    What's even worse (nothing is stopping you from overloading `operator+(int,base)` to call `operator+(base,int)`), this won't work when `b` is a `const b&`. While I'm sure that Alex knows what to do about that, it's nevertheless badly missing in an answer to what's obviously a C++ novice. – sbi Jun 03 '10 at 22:03
  • @sbi, OK, let me edit the question to make it more novice friently (I notice the same lack of the "obvious const" in all other answers, btw). – Alex Martelli Jun 04 '10 at 00:33
6

If you are searching for a standard operator+() implementation, then unfortunately that is impossible:

class X { 
public:
     virtual X operator+(X const &rhs) = 0;
};

This code cannot compile, because the compiler cannot return an abstract X class by value.

Kornel Kisielewicz
  • 55,802
  • 15
  • 111
  • 149
  • 4
    Could return X* or a smartpointer to X. Hell, he could write his own smart pointer class that's really just a std::shared_ptr and solve this that way. – Puppy Jun 03 '10 at 22:29
  • As Alex noted, this, too, misses a vital `const`. – sbi Jun 04 '10 at 07:22
3

Note : Question have been updated, making this answer less valid.

If you're description is correct, you're just forgetting to use the virtual keyword to specify the operator as virtual...

class Addable{
public:
    virtual int operator+ const ( const Addable& other ) = 0; // pure virtual
    virtual int operator+ const ( int number ) = 0; // pure virtual
};
Klaim
  • 67,274
  • 36
  • 133
  • 188
  • re: my comment on the original post, how would one actual call such a beast, given a pointer `Addable * px`? My c++ is a little sketchy. – kibibu Jun 03 '10 at 21:50
  • @kibibu: That's no problem. For user-defined types, `a+b` becomes either `operator+(a,b)` or `a.operator+(b)`, depending on how the operator is overloaded. The latter is, except for the funny function name which allows the infix syntax, no different from `a.f(b)`. – sbi Jun 03 '10 at 22:06
  • 2
    I still believe that designs involving virtual operators are nonsensical. – sbi Jun 03 '10 at 22:07
  • This depends on what you are trying to accomplish. For example, if you were to be implementing a dynamic-type script language such as Lua, one might suggest that polymorphic operators is right up that street. – Puppy Jun 03 '10 at 22:27
  • Never mind, I missed a response by @Jerry Coffin elsewhere. I didn't realize virtual function lookup happened through references as well as through pointers. – kibibu Jun 04 '10 at 02:36
  • @sbi:I'm not sure I'd go *quite* that far. Just for one example, I can imagine a class `functor` with `virtual void operator()()=0;` as making sense under some circumstances. – Jerry Coffin Jun 04 '10 at 04:39
  • @Jerry: Yes, you're right, I probably overshot, some other operators (unary prefix `*`, for example) might also be fine. But `operator+` is used with _values_, and value semantics and `virtual` just don't fit. – sbi Jun 04 '10 at 07:21
  • As Alex noted, this, too, misses a vital `const`. – sbi Jun 04 '10 at 07:21
1

I see two issues that you should address, or at the very least better understand. They both boil down to the fact that you have not resolved the pure virtual declaration in your base class, ana:

1) operator+(): Your class baba defines a different + operator than the base class. In particular, ana::operator+() is a unary + operator (accepts only one operand), while baba::operator+(baba& ali) is a binary operator (accepts two operands) on baba. You need to decide which to use and use it. If you want to use the binary + (which given your definition in baba is what I think you want) then you declare in ana:

virtual int operator+(const ana&) const =0;

and in baba:

virtual int operator+(const ana& ali) const {return x+ali.x; }  

Why this needs to be a pure virtual method in ana, since x is defined in ana is curious. It will do interesting things if you have other derived classes that do things differently (losing commutivity is likely to result). But I expect you have your reasons, so I won't question further.

2) operator=(ana&): You also have a problem with the assignment operator declarations. Again, you're not resolving the pure virtual. In ana you have: virtual void operator=(ana&)=0; while in baba you have: void operator=(baba &ali). The arguments are different since baba& is not the same as ana&; so the pure virtual declaration is again not resolved. In order to fix this, you probably want to change the declaration in ana to:

virtual void operator=(const ana&)=0

and in baba:

virtual void operator=(const ana& ali) { x=ali.x; }

I have similar concerns as to why you want to declare this as a pure virtual since, again, it assumes that different derived classes will implement it differently leading to interesting behavior. Again, I'm sure you have your reasons.

I do hope this helps.

andand
  • 17,134
  • 11
  • 53
  • 79
0

The syntax for a pure virtual function would be something like:

class X { 
public:
     virtual int operator+(X const &rhs) = 0;
};

Note, however, that you only rarely want to do this -- you typically want an overload of operator+ to be implemented as a free function, to allow conversion of the left operand (if necessary).

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • Fortunately hasan wants to return just an int. – user168715 Jun 03 '10 at 21:48
  • @kibibu:you probably wouldn't -- but contrary to your previous comment, a pointer isn't necessary; polymorphism via references is perfectly fine. Nonetheless, the whole thing is problematic. – Jerry Coffin Jun 03 '10 at 21:52
  • As Alex noted, this, too, misses a vital `const`. – sbi Jun 04 '10 at 07:23
  • @Jerry: Show me a sensible `operator+` that returns a reference. (Isn't that an item in _EC++_?) – sbi Jun 04 '10 at 07:23
  • @sbi: I specifically said "The syntax...", but then said, "you rarely want to do this" (and even the "rarely" is probably being generous -- I'm not sure you ever do). At least IMO, worrying about const correctness is pointless -- just don't do it. – Jerry Coffin Jun 04 '10 at 13:54
  • @Jerry: My comment about the sensible `operator+` was specifically regarding your comment to kibibu, where you didn't say most of these things. (I hadn't even seen that you are the one who posted this answer. Sorry for the confusion.) – sbi Jun 04 '10 at 18:34
  • @Jerry: Having taught C++ for a few years, I have learned that, when teaching, one needs to do it right every time. Beginners can't tell that a piece only cares about one thing (here: the silliness of `virtual`) and disregards other aspects of the code (here: constness), which shouldn't be disregarded in other contexts. Someone will fast-scan your answer, hopefully realizing that you say `virtual operator+` is rarely ever Ok, copy the code except for the `virtual`, and come back here asking why this fails to compile with a horrible error message when they have a `const` on the left side. – sbi Jun 04 '10 at 18:37
  • @sbi: I agree that an example of what to do should be exemplary in general, not just the aspect being demonstrated at the moment. This, OTOH, specifically says to use a free function instead; if somebody ignores that and uses it anyway, I doubt that adding `const` is going to help them. – Jerry Coffin Jun 04 '10 at 18:47
  • @Jerry: You haven't convinced me, but from now on we would just repeat ourselves, so I'm going to stop this. – sbi Jun 05 '10 at 07:19
0

 #include 
using namespace std;
class ana {
    protected :
    int x;
    public :

virtual int operator+()=0; virtual void operator=(ana&)=0; };

class baba:public ana{ public: baba(int k){x=k;} int operator+(baba &ali){ int k; k=x+ali.x; return k; } void operator=(baba &ali){ x=ali.x; }

};

int main(){ baba k(4);

return 0; }<code>what is wrong here?
hasan
  • 127
  • 1
  • 1
  • 4
  • Did you just ignore all the comments above? "int operator+(baba &ali);" is NOT overriding "virtual int operator+()=0;" - they have different arguments. – Colin Jun 03 '10 at 22:23
  • @Colin: I think he's added an answer by mistake instead of editing the question. This is the code we've been asking for. – Troubadour Jun 03 '10 at 22:29
  • I've added the code to your question. You can delete this answer. – Troubadour Jun 03 '10 at 22:31