A constructor is responsible for initializing an object. It can be overloaded to handle different types of inputs.
Why do we need multiple constructors? How does constructor overloading improve code flexibility?
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);
}
Modify the Value
class to include a constructor that accepts a boolean type.
The =
operator can be overloaded to customize assignment behavior.
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;
}
Allows conversion from an object to another type.
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;
}
Implement a cast overload to convert a Value
object to a floating-point number.
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;
}
Modify the extended example to include overloading of the +
operator for Value
objects.
Fraction
that overloads the +
operator for fraction addition.Value
class to support floating-point number conversion.==
operator to compare two Value
objects.*
operator to multiply two Value
objects.