Operator Overloading and Conversion

1. Constructor Overloading

A constructor is responsible for initializing an object. It can be overloaded to handle different types of inputs.

Discussion:

Why do we need multiple constructors? How does constructor overloading improve code flexibility?

Example:

class Value{
     public:
         std::string Data;
         Value(); // Default constructor
         Value(const Value &val); // Copy constructor
         Value(const std::string &str); // String constructor
         Value(int i); // int constructor
         Value(double d); // double constructor
};

Value::Value(){
}

Value::Value(const Value &val){
    Data = val.Data;
}

Value::Value(const std::string &str){
    Data = str;
}

Value::Value(int i){
    Data = std::to_string(i);
}

Value::Value(double d) {
    Data = std::to_string(d);
}


    

Exercise:

Modify the Value class to include a constructor that accepts a boolean type.

2. Assignment Operator Overloading

The = operator can be overloaded to customize assignment behavior.

Example:

class Value{
     public:
         std::string Data;
         Value &operator=(const Value &val); // assignment
};

Value &Value::operator=(const Value &val){
    if(this != &val){
        Data = val.Data;
    }
    return *this;
}

int main(){
    Value i{3};
    Value j;

    j = i; // same thing as j.operator=(i);
    return 0;
}

3. Cast Operator Overloading

Allows conversion from an object to another type.

Example:

class Value{
     public:
         std::string Data;
         operator int() const; // int cast
};

Value::operator int() const{
    return std::stoi(Data);
}

int main(){
    Value i{3};
    int j = 7;

    j = i; // same thing as j = i.operator int();
    return 0;
}

Exercise:

Implement a cast overload to convert a Value object to a floating-point number.

4. Extended Example

Example:


class Value{
     public:
         std::string Data;
         Value(const Value &val); // Copy constructor
         Value(int i); // int constructor
         Value &operator=(const Value &val); // assignment
         operator int() const; // int cast
      
};

Value::Value(const Value &val){
    Data = val.Data;
}

Value::Value(int i){
    Data = std::to_string(i);
}

Value &Value::operator=(const Value &val){
    if(this != &val){
        Data = val.Data;
    }
    return *this;
}

Value::operator int() const{
    return std::stoi(Data);
}

int main(){
    Value i{3}, k{4};
    int j = 7;
    k = j + i;
    // k.operator=(Value(j + i.operator int());
    return 0;
}


    

Exercise:

Modify the extended example to include overloading of the + operator for Value objects.

Practice Problems

Put your solutions here
  1. Implement a class Fraction that overloads the + operator for fraction addition.
  2. Modify the Value class to support floating-point number conversion.
  3. Overload the == operator to compare two Value objects.
  4. Overload the * operator to multiply two Value objects.