Wherever I search, I find that to use a method without an object, THE ONLY WAY IS TO MAKE IT STATIC. However,
in the following piece of code I show two examples of non static methods being called without an object FindIngredient
and NumPizzas()
((*) and (**)). It compiles and not even warnings are given. As you can see I am not using static anywhere
How come it is possible?
class Ingredient {
public:
string Name;
int Price;
string Description;};
class Pizza {
vector<Ingredient> ingredients;
public:
string Name;
void AddIngredient(const Ingredient& ingredient){ingredients.push_back(ingredient);}
};
class Pizzeria {
map<string, Ingredient> mapNameToIngredient;
map<string, Pizza> mapNameToPizza;
void AddPizza(const string &name, const vector<string> &ingredients)
{
if(mapNameToPizza.find(name) != mapNameToPizza.end())
{
throw runtime_error("Pizza already inserted");
}
else
{
Pizza pizza;
pizza.Name = name;
for(size_t i = 0; i < ingredients.size(); i++)
{
Ingredient ingredient= FindIngredient(ingredients[i]); //(*)
pizza.AddIngredient(ingredient);
}
mapNameToPizza[name] = pizza;
}
}
void AddIngredient(const string &name, const string &description, const int &price)
{
if(mapNameToIngredient.find(name) != mapNameToIngredient.end())
{
throw runtime_error("Ingredient already inserted");
}
else
{
Ingredient ingredient;
ingredient.Name = name;
ingredient.Price = price;
ingredient.Description = description;
mapNameToIngredient[name] = ingredient;
}
}
const Ingredient &FindIngredient(const string &name) const
{
auto it = mapNameToIngredient.find(name);
if(it != mapNameToIngredient.end())
{
return it->second;
}
else
{
throw runtime_error("Ingredient not found");
}
}
};
class Order {
vector<Pizza> pizzas;
public:
int numOrder;
int NumPizzas() const { return pizzas.size(); }
int ComputeTotal() const;
{
int total = 0;
for(size_t i = 0; i < (size_t)NumPizzas(); i++) //(**) why is it letting me use the method as a static function?
{
total += pizzas[i].ComputePrice();
}
return total;
}
};
When you call a member function from another member function, the object is implied - it's this->
.