Fruit Struct

Fruit Struct

Create a Fruit struct that only contains the member variable std::string name. Create a function that takes a Fruit object as its only parameter and prints its name. Show how a string can be automatically cast to a Fruit object when passed to the function by creating a constructor. Then, modify the Fruit struct to use the explicit keyword and show how to explicitly create Fruit objects to pass to the function.

Answer

Printing the fruit name from a string passed to the function:

#include <iostream>
#include <string>

struct Fruit {
    std::string name;

    // Constructor with a string parameter
    Fruit(const std::string& n) {
        name = n;
    }
};

void print_fruit_name(const Fruit& fruit) {
    std::cout << "Fruit name: " << fruit.name << std::endl;
}

int main() {
    // Implicit conversion from string to Fruit
    print_fruit_name("Apple");

    // Explicit creation of a Fruit object
    Fruit banana("Banana");
    print_fruit_name(banana);

    return 0;
}

The automatic type conversion that happens with "Apple"doesn't occur when the constructor is declared as explicit.

    explicit Fruit(const std::string& n) {
        name = n;
    }

Instead, you have to create an object with "Apple" first. This can be done by defining an object with an identifier.

    Fruit apple("Apple");
    print_fruit_name(apple);

Or by creating an object to directly pass into the function:

print_fruit_name(Fruit("Apple"));
Questions