WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

C++ · Intermediate · question 24 of 100

Explain the concept of operator overloading in C++ with an example.?

📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

Operator overloading is a feature in C++ that allows operators such as +, -, *, /, etc. to be overloaded for user-defined classes. This means that we can define how operators should work with objects of our classes. For example, we can define how the + operator should work with objects of our class, allowing us to add two objects together using the + operator.

Here’s an example of operator overloading in C++:

    #include <iostream>
    using namespace std;
    
    class Point {
        public:
        Point(int x = 0, int y = 0) : x(x), y(y) {}
        Point operator+(const Point& other) {
            Point temp;
            temp.x = x + other.x;
            temp.y = y + other.y;
            return temp;
        }
        void print() {
            cout << "(" << x << "," << y << ")" << endl;
        }
        private:
        int x, y;
    };
    
    int main() {
        Point p1(1, 2);
        Point p2(3, 4);
        Point p3 = p1 + p2;
        p3.print();
        return 0;
    }

In this example, we define a class called Point that represents a point in two-dimensional space. The class has two private data members, x and y, that represent the coordinates of the point. We define a constructor to initialize the data members, and a print() function to print the coordinates of the point.

We also overload the + operator for the Point class. The operator takes a reference to another Point object, adds the x and y coordinates of both points, and returns a new Point object with the result. This allows us to add two Point objects together using the + operator.

In the main() function, we create two Point objects, p1 and p2, with coordinates (1, 2) and (3, 4) respectively. We then add these two points together using the + operator, and store the result in a new Point object called p3. We then print the coordinates of p3 using the print() function.

This example demonstrates how we can define how operators should work with objects of our classes, allowing us to use familiar operators like + to perform custom operations on our objects. Operator overloading can make our code more readable and easier to understand, and can simplify complex operations by using familiar syntax.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic C++ interview — then scores it.
📞 Practice C++ — free 15 min
📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

All 100 C++ questions · All topics