Fihop
Fihop

Reputation: 3177

operator keyword in c++

I'm reading thinking in C++. There is a code fragment that I don't understand. Can anyone help me explain it?

class GameBoard {
public:
  GameBoard() { cout << "GameBoard()\n"; }
  GameBoard(const GameBoard&) { 
    cout << "GameBoard(const GameBoard&)\n"; 
  }
  GameBoard& operator=(const GameBoard&) {
    cout << "GameBoard::operator=()\n";
    return *this;
  }
  ~GameBoard() { cout << "~GameBoard()\n"; }
};

class Game {
  GameBoard gb; // Composition
public:
  // Default GameBoard constructor called:
  Game() { cout << "Game()\n"; }
  // You must explicitly call the GameBoard
  // copy-constructor or the default constructor
  // is automatically called instead:
  Game(const Game& g) : gb(g.gb) { 
    cout << "Game(const Game&)\n"; 
  }
  Game(int) { cout << "Game(int)\n"; }
  Game& operator=(const Game& g) {
    // You must explicitly call the GameBoard
    // assignment operator or no assignment at 
    // all happens for gb!
    gb = g.gb;
    cout << "Game::operator=()\n";
    return *this;
  }
  class Other {}; // Nested class
  // Automatic type conversion:
  operator Other() const {
    cout << "Game::operator Other()\n";
    return Other();
  }
  ~Game() { cout << "~Game()\n"; }
};

In the above code fragment, I don't understand:

  operator Other() const {
    cout << "Game::operator Other()\n";
    return Other();
  }

I guess this function define an operator "Other()". What doe it mean for returning Other()? If Other() means an object of class Other, the return type of operator "Other()" is not a type of class Other.

Upvotes: 0

Views: 371

Answers (3)

Pete Becker
Pete Becker

Reputation: 76245

It is a conversion operator (NOT a cast operator). Whenever your code calls for a conversion to Other the operator will be used. There are two ways your code can call for a conversion. An implicit conversion occurs in situations like this:

Game g;
Game::Other o(g); // **implicit conversion** of g to Game::Other

An explicit conversion occurs when you write a cast in your code:

Game g;
Game::Other o(static_cast<Game::Other>(g)); // **explicit conversion**
    // of g to Game::Other

Upvotes: 2

user1887276
user1887276

Reputation:

This is a C++ casting operator. It defines what happens if an object will be casted to class Other.

Upvotes: 0

It is a cast operator.

When you'd write (Other)game; (i.e. you cast a game to Other).

It will be called.

Upvotes: 0

Related Questions