Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy do I get SIGSEGV error when use class function from pointer?
    primarykey
    data
    text
    <p>I'm new in C++ and runned into first trouble. I have a GameObject class in which I have to somehow store many components. Each component is a different class, so I can't just normally use vector. I decided to store a component's type and pointer to that object. The problem is, that when I get, return that component, and use a class function which uses it's member variables, I get SIGSEGV error(yeah, sounds confusing). However, if I normally use that class and that function, I don't get a SIGSEGV error.</p> <p><strong>GameObject.h:</strong></p> <pre><code>enum ComponentType { MeshComponent // currently only one type }; struct Component { ComponentType type; void *pointer; }; class GameObject { private: std::vector&lt;Component&gt; components; public: void addComponent(ComponentType type); template&lt;typename T&gt; T* getComponent() { for(std::vector&lt;Component&gt;::size_type i = 0; i != components.size(); i++) { // will need to somehow check T type later if(components[i].type == MeshComponent) { return (Mesh*)&amp;components[i].pointer; } } Debug::Loge(GAMEOBJECT_TAG, "No %s component in %s gameobject!", componentTypeToString(MeshComponent).c_str(), name.c_str()); return 0; } } </code></pre> <p><strong>GameObject.cpp:</strong></p> <pre><code>void GameObject::addComponent(ComponentType type) { Component component; component.type = type; if(type == MeshComponent) { Mesh *mesh = new Mesh(); component.pointer = &amp;mesh; } components.push_back(component); } </code></pre> <p><strong>Mesh.h</strong></p> <pre><code>class Mesh { public: Mesh *setMeshData(std::vector&lt;GLfloat&gt; data); }; </code></pre> <p><strong>Mesh.cpp</strong></p> <pre><code>Mesh *Mesh::setMeshData(vector&lt;GLfloat&gt; data) { meshData = data; return this; } </code></pre> <p>And finally this is how I use it:</p> <pre><code>GameObject object; void somefunction() { object.addComponent(MeshComponent); object.getComponent&lt;Mesh&gt;()-&gt;setMeshData(triangle_data); // SIGSEGV HERE!! // if I use this one instead above - no sigsegv, everything is fine. Mesh mesh; mesh.setMeshData(triangle_data); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload