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;
}
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;
}
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.
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