0

I do not understand why the initialiser for Item_Base accepts another object as a valid input. I assume there is some implicit overload being used here?

class Item_Base 
{
public:
  Item_Base(const std::string& item_name);
  ~Item_Base(void);
  std::string tostr();
private:
  const std::string name;
};

Item_Base::Item_Base(const std::string& item_name)
:name(item_name)
{
  std::cout << "Constructing: " << name << std::endl;
}

Item_Base::~Item_Base(void)
{
  std::cout << "Destructing: " << name << std::endl;
}

std::string Item_Base::tostr()
{
  return name;
}

int main(int argc, char **argv)
{
  Item_Base red_book("Red Book");
  Item_Base green_bow("Green Bow");
  Item_Base copy_test = red_book;
  Item_Base init_test(green_bow); // Why does this work?

  std::cout << red_book.tostr() << std::endl;
  std::cout << green_bow.tostr() << std::endl;
  std::cout << copy_test.tostr() << std::endl;
  std::cout << init_test.tostr() << std::endl;

  return 0;
}

Output

Constructing: Red Book
Constructing: Green Bow
Red Book
Green Bow
Red Book
Green Bow
Destructing: Green Bow
Destructing: Red Book
Destructing: Green Bow
Destructing: Red Book

1 Answers1

0

If you want to prevent copying and assignment, simply delete those methods:

Item_Base(const Item_Base&) = delete;
Item_Base& operator=(const Item_Base&) = delete;
John Zwinck
  • 239,568
  • 38
  • 324
  • 436