I come from the Java background, but after that I learned C ++ and programmed it for several years (mainly debugging and recording fixes, not developing programs from scratch). However, I ran into a problem today and, frankly, I am a little surprised that it took a long time to meet her.
Let's say I have a class called Class1 whose header file contains (among other code):
class Class1 { private: Class2 object; }
Class2 does not have a specified default constructor. Now, in the Class1 constructor, I read the binary header of the file and use the information that I parse to initialize Class2, as shown below using pseudocode:
Class1::Class1(std::string) {
In Java, since it does not use the RAII paradigm, this would be completely legal. However, since C ++ uses RAII, object 2 has already been initialized using its default constructor when I do object2 = Class2(info); . I could not just name this constructor initially (in the Class1 header file) because I did not have the information I needed to create an object . However, I cannot just make object2 local to the constructor, because I need other functions to see / use it.
Clearly this does not work. What is the standard approach for this? I really thought that I just changed Class1 to a class 2 pointer:
class Class1 { private: Class2* objectPointer; }
and then calling *objectPointer = Class2(info) . However, "Class2" in my case is ifstream, and it seems that the operator= function has been removed and does not work with any of the approaches.
So ... how to do this?