I searched the topic many times on the Internet, and I really did not find a solid answer. As a C # programmer, I’m used to declaring classes in a large scope, usually at the top of the file, outside of any functions, and then constructing them when used.
Moving to C ++, the only way to replicate this is to create a default constructor, and that’s fine, but in some cases I would rather have a constructor that requires arguments than a default constructor without arguments.
After searching the Internet for a solution, I found some tips that have their drawbacks:
1. Pointers
Some people suggested having a dynamic pointer in the desired area, and then assign a pointer to indicate the location of the class when creating it.
CClass* pClass = 0; int main() { pClass = new CClass(1337); delete pClass; return 0; }
The problem with this approach is that you have to remember that you delete the pointer later, so static pointers are much more "safe". In addition, I assume that it will be a small lack of memory, although not very, due to the presence of a pointer.
2. There is a default design by default
In any case, it is recommended to have a default constructor that just zeros everything inside the class:
class CClass { public: CClass() : leetNumber(0) {} CClass(int leetNumber) : leetNumber(leetNumber) {} private: int leetNumber; };
But what happens if you can't just reset everything inside the class? What if you have another class that cannot be simply initialized to anything? What will you do if a user tries to access a function inside a class without properly initializing members? (You can verify this, but I believe that this will require too much code, especially if you have many members).
3. Staying in a smaller, more local area
There were suggestions on which people said that they remain in a small amount, pass the class as a reference to other functions that it may need, and construct it as soon as they declare the class:
class CClass { public: CClass(int leetNumber) : leetNumber(leetNumber) {} int getLeetNumber() { return leetNumber; } private: int leetNumber; }; bool GetMuchNeededAmazingNumberFromClass(CClass& myClass) { if(myClass.getLeetNumber() == 1337) return true; return false; } int main() { CClass myClass = CClass(1337); if(!GetMuchNeededAmazingNumberFromClass(&myClass); return 1; return 0; }
This is good in the sense that you can see which function needs something, but I can imagine a function that requires a large number of external classes that have a huge number of necessary arguments.
There are many more examples, but I can’t find what I can rely on, especially against C #, where this material is nice and light.
Thanks.
EDIT:
Let me tell you more about what I ask - in C # you can do the following:
public class Program {
This allows me to create a class without creating it, this is what I am looking for in C ++.
Thanks again.