Since Shape::vertices
is a pointer you are just rebinding it to a different object when you do
myShape->vertices = &vertices
you are not copying vertices
into Geometry::vertices
as you have figured out.
While I do not agree with your approach (it violates, among several other things, the open/closed principle), you can achieve what you wanted by returning a reference to Geometry::vertices
instead.
private:
Geometry geometry;
public:
vector<vec3>& Shape::vertices() { return geometry->vertices;}
And use:
myShape->vertices() = vertices;
A better strategy:
- Avoid unmanaged resource acquisition in constructors. You are acquiring an instance of
Geometry
object in the constructor and assigning it to a raw pointer. This could lead to problems, e.g. what would happen to that object if your constructor fails? In general, it is a good habit to observe RAII. That would be by using smart pointers in your case.
In code:
Shape::Shape(): geometry(new Geometry()) {}
private:
std::unique_ptr<Geometry> geometry;
- Do not expose member variables: I don't think it is ever a good idea to expose the data members of a class let alone a pointer data member. By exposing data members 1) you are requiring the user knowledge of your class to go beyond what your class does to how it is implemented. 2) you are closing the door to future changes in your internal implementation without refactoring all your class users codes. 3) your class members are often invariant of that class, by exposing them users will potentially break things down.
To sum up, I would redesign your code in this way:
class Geometry
{
private:
std::vector<vec3> vertices;
public:
void addVertex(vec3& vtx) { vertcies.push_back(vtx);}
void addVertices(std::vector<vec3>& vtxs) { for(auto& vtx:vtxs){ vertices.push_back(vtx);}}
}
class Shape
{
private:
std::unique_ptr<Geometry> geometry;
public:
Shape(): geometry(new Geometry()) {}
void addVertex(vec3& vtx) { geometry->addVertex(vtx);}
void addVertices(std::vector<vec3>& vtx) { geometry->addVertices(vtxs);}
}
P.S. I assumed that your Geometry::vertices
is of type vector<vec3>
as implied in your question..