I have been reading a lot of tutorials on C++ class but they miss something that other tutorials include.
Can someone please show me how to write and use a very simple C++ class that uses visibility, methods and a simple constructor and destructor?
I have been reading a lot of tutorials on C++ class but they miss something that other tutorials include.
Can someone please show me how to write and use a very simple C++ class that uses visibility, methods and a simple constructor and destructor?
Even if he is a student, worth trying to answer because it is a complex one not that easy at least for a new Visitor of C++ :)
Classes in C++ serve an intersection of two design paradigms,
1) ADT :: which means basically a new type, something like integers 'int' or real numbers 'double' or even a new concept like 'date'. in this case the simple class should look like this,
this is the most basic skeleton of an ADT... of course it can be simpler by ignoring the public area! and erasing the access modifiers (public, private) and the whole thing will be private. but that is just nonsense. Because the NewDataType becomes useless! imagine an 'int' that you can just declare but you CAN NOT do anything with it.
Then, you need some useful tools that are basically not required to the existence of the NewDataType, but you use them to let your type look like any 'primitive' type in the language.
the first one is the Constructor. The constructor is needed in many places in the language. look at int and lets try to imitate its behavior.
every line of the above lines is a declaration, the variable gets constructed there.
and in the end imagine the above int variables in a function, that function is called 'fun',
you see the magical line, here you can tell the compiler any thing you want! after you do every thing and your NewDataType is no more useful for the local scope like in the function, you KILL IT. a classical example would be releasing the memory reserved by 'new'!
so our very simple NewDataType becomes,
Now this is the very basic skeleton, to start building a useful class you have to provide public functions.
there are A LOT of tiny tools to consider in building a class in C++,
. . . .
2) Object :: which means basically a new type, but the difference is that it belongs to brothers, sisters, ancestors and descendants. look at 'double' and 'int' in C++, the 'int' is a sun of 'double' because every 'int' is a 'double' at least in concept :)
Well documented example taken and explained better from Constructors and Destructors in C++:
Silly, but, there you are. Note that "visibility" is a misnomer: public and private control accessibility, but even "private" stuff is still "visible" from the outside, just not accessible (it's an error to try and access it).