I am making a scheduling program as an exercise. What I have so far compiles fine, but when testing it, the program crashes when I hit this part:
1 2 3 4 5 6 7
for (int i = 0; i < x; i++)
{
string name;
cout << "\nEnter name: ";
getline(cin, name);
ret.push_back(MyObject(name));
}
"ret" is a vector. The program errors out and returns 0xC0000005 to the console after I enter a name. It doesn't matter what name I enter, how long it is, etc.
The problem is that you did not declared a copy constructor in your class MyObject. So the compiler uses an impliciitly defined copy constructor. As you do not initialize member options I think that assignment a velue by the implicitly defined copy constructor results in faliure.
Try to declare you copy constructor and initialize all members of your class in constructors.
To continue, the reason for the crash is the variable MyOption *options. Your copy constructor, MyObject(const MyObject& old), needs to create a new options, along the lines of:
1 2 3 4 5 6 7 8 9
class MyClass
char* word;
public:
MyClass(const MyClass& old)
{
word = newchar[strlen(old.word) + 1];
strcpy(word, old.word);
}
Otherwise, I think you're pointers just get copied and you can't delete the same pointer twice during the destructor.
I just started learning C++, so this is kind of over my head. I assume that I need it because when I use push_back like that, I'm actually creating a temporary MyObject which gets copied into a new MyObject in the space allocated by the vector?
Where can I learn more about copy constructors? The tutorial here doesn't really get into them.
Also, I tried adding this function to my class and it worked:
1 2 3 4 5 6
MyObject(const MyObject &old)
{
name = old.name;
num_options = old.num_options;
options = new MyOption[num_options];
}
But when I tried adding a loop in order to copy the options over, it failed.
1 2 3 4 5 6 7 8 9 10
MyObject(const MyObject &old)
{
name = old.name;
num_options = old.num_options;
options = new MyOption[num_options];
for (int i = 0; i < num_options; i++)
{
options[i] = old.options[i];
}
}
I made sure to add a copy constructor function to the MyOption class too.
I figured out why the loop failed. It's because in the MyObject constructor, I only set the name and didn't set num_options to 0. When I changed it to this:
the loop in the copy constructor works correctly, for what I have so far in my program anyway.
The copy constructor in the MyOption class is set up like MyOption(const MyOption &old), similarly to MyObject. In my loop, I use the = sign, so is the copy constructor being called at all?
If I try to use options[i](old.options[i]);, the compiler will give me an error.