5 ms·
Well, the key thing is the `reason` here. In C++ we use RAII, so this is the reason to have a member constructor/destructor functions instead of non-member crea
by zura 12y ago
Well, the key thing is the `reason` here. In C++ we use RAII, so this is the reason to have a member constructor/destructor functions instead of non-member create_something(...)/destroy_something(...) (aka C style).
But, for instance, `sort` is a good candidate to have outside of a class - and it actually is a global function - std::sort.
- throwawayaway 12y agoRAII is your reason. When you start preferring non member functions, you tend allocate on the stack. There are rare items that require heap allocation and other resources. For those you can have classes. What I am saying is that when you prefer non member functions you end up with very few classes.
- nikbackm 12y agoYou don't use classes only to get RAII. They are also useful when you have data with invariants, which the constructor establishes. And of course, if you want to use private data.
- throwawayaway 12y agoby invariants do you mean constant values? there's many ways to implement private data. if you prefer non member functions, a class is a bunch of extra keystrokes to achieve the same as the old fashioned C private data. if you prefer non member functions to member functions, your private data becomes a global variable or struct in a file, and the private data is not accessible by getter/setter functions that are externalised.
- zura 12y agoHaving access to private data (implementation details) is another reason to have a member function. Unless you're a fan of `friend` keyword ;)
- throwawayaway 12y agoi think you need to read my comment again because "private:" in a class is not the only way to implement private data. you are only repeating what the parent commenter said.
- zura 12y agoWell, to follow your line - virtual functions can also be implemented with some function pointer stuff within C. We're not discussing implementing various C++ stuff in C, we're talking about C++ itself.
- throwawayaway 12y agobe that as it may, it requires more keystrokes to implement virtual functions in C than it does in C++. however, it requires less keystrokes to implement private data in C, than it does to create a class to store private data. therefore it's questionable, if you are preferring non member non friend functions, whether you should use classes when you want private data. i refute the idea that private data is a reason to use classes, if you are preferring non member non friend functions as advocated by Stroustrup, Meyers and Stepanov. as i said already > There's very little reason for class members unless you want inheritance or polymorphism.