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
What is the difference between inheritance and polymorphism?
Can you inherit a private class?
write a program to enter a string like"sunil is a good boy and seeking for a job" not more than 10 characters including space in one line,rest characters should b in other line.if the next line starts from in between the previous word,then print whole word to next line.
which feature are not hold visual basic of oop?
What is the point of oop?
is there any choice in opting subjects like 4 out of 7
What is a null tree?
INSTANCE FIELDS DECLARED private ARE ACCESSIBLE BY THE METHODS ONLY.CAN WE CHANGE THE private FIELD OF AN OBJECT IN A METHOD OF SOME OTHER OBJECT OF THE SAME CLASS?
if i have same function with same number of argument but defined in different files. Now i am adding these two files in a third file and calling this function . which will get called and wht decide the precedence?
What do you mean by abstraction?
write a C++ program for booking using constructor and destructor.
What is polymorphism what is it for and how is it used?
What is pure oop?
what are the ways in which a constructors can be called?
How to use CMutex, CSemaphore in VC++ MFC