I have ended up running into a specific problem in my own C++ project which is now crashing (throwing a segmentation fault error). I have created an entire project, which I have pasted below, which essentially recreates all of the code/classes/methods that are related to the segmentation fault error in as simple a form as possible. The project below behaves in exactly the same way as my more complicated personal project in that:
- it crashes due to a segmentation fault, and
- it runs successfully if the datatype used throughout the project is switched to being an integer instead of a string.
Does anyone have a clue why this would be? I am a lost, beginner programmer, and the error/debugger messages in Codeblocks are not helping me out much (although I don't exactly know for what to look--emphasis on beginner programmer).
An idea of what the code is doing in general: I have an array of child objects stored within a parent object. Every child object has a single attribute of type string. I want to be able to retrieve ("get") that attribute value of a specific child object stored within a given parent object, passing the "child objects array" index as a parameter.
main.cc
Code:
#include <iostream>
#include "parent.h"
int main() {
Parent ParentObject;
std::cout << ParentObject.BadassGetObjectAttribute(5) << std::endl;
}
parent.cc
Code:
#include "parent.h"
std::string Parent::BadassGetObjectAttribute(int x) {
array_of_children[x].GetObjectAttribute();
}
parent.h
Code:
#ifndef PARENT_H
#define PARENT_H
#include "child.h"
class Parent {
public:
std::string BadassGetObjectAttribute(int);
private:
Child array_of_children[20];
};
#endif
child.cc
Code:
#include "child.h"
Child::Child() {
object_attribute = "this string is initialized";
}
std::string Child::GetObjectAttribute() {
return object_attribute;
}
child.h
Code:
#ifndef CHILD_H
#define CHILD_H
#include <string>
class Child {
public:
Child();
std::string GetObjectAttribute();
private:
std::string object_attribute;
};
#endif