Examveda

Given the following C++ code. How would you define the < operator for Box class so that when boxes b1 and b2 are compared in if block the program gives correct result?
#include <iostream>
#include <string>
using namespace std;
class Box
{
    int capacity;
    public:
    Box(){}
    Box(double capacity){
        this->capacity = capacity;
	}
};
int main(int argc, char const *argv[])
{
    Box b1(10);
    Box b2 = Box(14);
    if(b1 < b2){
	cout<<"Box 2 has large capacity.";
    }
    else{
	cout<<"Box 1 has large capacity.";
	}
    return 0;
}

A.

bool operator<(Box b)
{
    return this->capacity < b.capacity ? true : false;
}

B.

bool operator<(Box b)
{
    return this->capacity > b.capacity ? true : false;
}

C.

bool operator<(Box b)
{
    return  b1 > b2 ? true : false;
}

D.

bool operator<(Box b)
{
    return this < b ? true : false;
}

Answer: Option A


Join The Discussion

Related Questions on Classes and Objects in C plus plus