Which is the only operator in C++ which can be overloaded
but NOT inherited?

Answer Posted / sharathnasa

#include <iostream>
#include <iomanip>

using namespace std;

class A {
public:
int _i;
A(int i) : _i(i) { }
virtual A &operator=(A const &other) {
if (this!=&other) {
_i = other._i;
}
return *this;
}
virtual A operator+(A const &rvalue) {
return A(_i + rvalue._i);
}
virtual void print() {
cout << "A(_i=" << _i << ")";
}
};

class B : public A {
public:
int _j;
B(int i, int j) : A(i), _j(j) { }
virtual void print() {
cout << "B(_i=" << _i << ", _j=" << _j <<")";
}
};

int main() {
A a1(5), a2(3);
a1.print();
cout << " + ";
a2.print();
cout << " = ";
A a3 = a1 + a2;
a3.print();
cout << endl;

B b1(5,3), b2(3,5);
b1.print();
cout << " + ";
b2.print();
cout << " = ";

// this works, although (b1+b2) returns an A since it uses
A's operator+
(b1+b2).print();

// this does not work: no conversion from A to B, i.e.
operator= not inherited
// B b3 = b1 + b2;
// b3.print();
cout << endl;

return 0;
}

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What are the benefits of interface?

581


What is inheritance in simple words?

627


What does oop mean in snapchat?

686


Why polymorphism is used in oops?

585


Where You Can Use Interface in your Project

1427






write a program to find 2^n+1 ?

1551


Why do we use polymorphism?

579


Which language is pure oop?

551


why reinterpret cast is considered dangerous?

1903


What is polymorphism and types?

602


What is basic concept of oop?

700


Why is encapsulation used?

577


Get me an image implementation program.

1559


What are properties in oop?

611


What does sksksk mean in text slang?

1537