0

I am learning C++ in Qt environment and I was going through one of the sample code online. Can anyone please explain this syntax to me?

const TicTacToe * GetTicTacToe() const { return m_tictactoe.get(); }

Why is there a const before the opening bracket of a function? Is it a pointer or multiplication?

the full class is as follows, but the syntax of the instructions mentioned above is not clear to me

class QtTicTacToeWidget : public QWidget
 {
   Q_OBJECT
   public:
      explicit QtTicTacToeWidget(QWidget *parent = 0);
      const TicTacToe * GetTicTacToe() const { return m_tictactoe.get(); }
      void Restart();
Aurelius
  • 11,111
  • 3
  • 52
  • 69

2 Answers2

1

The first const is to signify that the variable pointer TicTacToe can't be changed. The second constant after the function declaration says that anything that happens inside this function will not change any member variable inside the class. Because it effectively does not change memory data on the class, it can be used when you use any constant object of that class. For example:

const QtTicTacToeWidget myConstObject;
// Since myConstObject is a constant, I am not allowed to change anything inside
// the class or call any functions that may change its data.  A constant function
// is a function that does not change its own data which means I can do this:
myConstObject.GetTicTacToe();

// But I can not do the next statement because the function is not constant
// and therefore may potentially change its own data:
myConstObject.Restart();
Lochemage
  • 3,974
  • 11
  • 11
  • Thank you so much for your detailed reply...It certainly did clear everything regarding the 'const' used there... Can you also explain the use of asteric '*' in the same bold line? Here are we making the full function a pointer of type TicTacToe? – Inquisitive Aug 08 '13 at 22:41
  • that is just the return value of the function, it returns you a pointer to a TicTacToe object. – Lochemage Aug 08 '13 at 22:47
0

The const between before the opening bracket signifies that the function is a const member function. It essentially says that it guarantees to not modify the class and therefore can be called on an object declared as const.

Well that, and it also allows the function to modify mutable variables in a const class.

Chris Cooper
  • 431
  • 3
  • 13
  • Thanks alot for your reply....I wasn't sure about mutable variables but then I googled it and learnt something new... so, as far as I understand, in a constant function we can modify selected variables if we had declared them mutable – Inquisitive Aug 08 '13 at 22:44
  • Yes, but don't use that as an excuse to suddenly mark everything as mutable. It's useful for when a class is logically const, but still needs to modify some data for functionality, such as reference counting. – Chris Cooper Aug 08 '13 at 23:39