454,925 Members | 1,134 Online Need help? Post your question and get tips & solutions from a community of 454,925 IT Pros & Developers. It's quick & easy.

# nonmember function

 P: n/a I d rather have a Matlab syntax such as: // create a Matrix of size 3,4 and fills it w/ random values. Matrix M=rand(3,4) But since this function changes the state of the object, I ought to make it a member function. ie. Matrix M(3,4); M.rand(); which I dont really like too much. What is my best option (while maintaining a matlab-like notation)? Aug 1 '05 #1
3 Replies

 P: n/a bl**********@gmail.com wrote: I d rather have a Matlab syntax such as: // create a Matrix of size 3,4 and fills it w/ random values. Matrix M=rand(3,4) But since this function changes the state of the object, I ought to make it a member function. ie. Matrix M(3,4); M.rand(); which I dont really like too much. What is my best option (while maintaining a matlab-like notation)? Add a static function to your 'Matrix' class template and let it create another instance of 'Matrix'. It's called "a factory method": template class Matrix { ... public: static Matrix rand(int n, int m) { Matrix temp(n, m); ... // randomize them return temp; } }; Matrix M = Matrix::rand(3, 4); You could of course simply have a non-member function, but it would need to be a template: template Matrix rand_matrix(int n, int m) { ... } and then you call it: Matrix M = rand_matrix(3, 4); V Aug 1 '05 #2

 P: n/a > I d rather have a Matlab syntax such as: // create a Matrix of size 3,4 and fills it w/ random values. Matrix M=rand(3,4) But since this function changes the state of the object, I ought to make it a member function. Not really. If rand() can alter the object state via public interface then it should be a non-member function, if not, you can still consider making rand() a friend of Matrix<>. ie. Matrix M(3,4); M.rand(); which I dont really like too much. Neither do I. What is my best option (while maintaining a matlab-like notation)? Answered above. Aug 3 '05 #3

 P: n/a bl**********@gmail.com schreef: I d rather have a Matlab syntax such as: // create a Matrix of size 3,4 and fills it w/ random values. Matrix M=rand(3,4) But since this function changes the state of the object No, it doesn't. If you want to "change the state of an object" there must be an object state before and after". In this case, there is no Matrix before. Therefore, rand() doesn't change it. The syntax you have is quite good. However since rand() is a quitegeneric name, I'd prefer a static Matrix::rand(). That makes it quite clear: Matrix M = Matrix::rand(3,4); HTH, Michiel Salters Aug 3 '05 #4

### This discussion thread is closed

Replies have been disabled for this discussion. 