You must Sign In to post a response.
  • C++ program to overload assignment operator.


    Are you preparing for Object Oriented Programming exams? Searching for detailed solution to write a C++ program using an overload operator? Here,on this page find answers to your question from our ISC experts.

    Following is a question that was asked in the question paper of B.E. Mechanical Engineering (June/July 2017)conducted by Bangalore University, for subject Object Oriented Programming(2K11 Scheme)(ME-601), Semester-VI

    This question is asked for 10 marks and hence requires some explanation. Please let me know the solution.

    Q) Write a C++ program to overload assignment operator. [10 Marks]
  • Answers

    1 Answers found.
  • As of you know, the assignment operator is '=' which is used to copy values from one object to another(already existing object). You can override this operator just like any other operators. We should write our own assignment operator same as Copy Constructor. There is no need to write an assignment operator when a class doesn't contain pointers. For every class, by default there will be a copy constructor and assignment operator. Compiler ensures that.

    The following example shows overriding of assignment operator :

    #include
    using namespace std;

    class DistanceCalculation {
    private:
    int ft; // 0 to infinite
    int inch; // 0 to 12

    public:
    // required constructors
    DistanceCalculation() {
    ft = 0;
    inch = 0;
    }
    DistanceCalculation(int f, int i) {
    ft = f;
    inch = i;
    }
    void operator = (const DistanceCalculation &D ) {
    ft = D.ft;
    inch = D.inch;
    }

    // method to display distance
    void displayDistance() {
    cout << "F: " << ft << " I:" << inch << endl;
    }
    };

    int main() {
    DistanceCalculation D1(11, 10), D2(5, 11);

    cout << "First Distance : ";
    D1.displayDistance();
    cout << "Second Distance :";
    D2.displayDistance();

    // use assignment operator
    D1 = D2;
    cout << "First Distance :";
    D1.displayDistance();

    return 0;
    }

    The output of the above code will be like the following :

    First Distance : F: 11 I:10
    Second Distance :F: 5 I:11
    First Distance :F: 5 I:11

    “It takes a great deal of bravery to stand up to our enemies, but just as much to stand up to our friends."
    – Albus Dumbledore, Harry Potter and the Sorcerer's Stone, Chapter 17


  • Sign In to post your comments