Jump to content
  • Advertisement
Sign in to follow this  
OpenGL_Guru

Copy Constructors, passing structs

This topic is 4329 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

hi all i wanted to get some feedback on this as i really havent done this much. what i have are 2 classes. class A has a struct that can hold the following:
struct var
   {
    string name;
    string units;
    string value_type;
    string min;
    string max;
   };

   struct data
   {
    var *variables;
    int num_vars;
   };

   data myStruct;


In class A i will fill up the data struct and once i am ready to pass that data the Class B i go through and allocate the memory to fill up the variables. simple enough. now i would to be able to take that struct and pass it to Class B's constructor as a parameters. not as a pointer but i need to make a copy for reasons i wont go into. is the easiest way to do this would be to create the same struct in Class B and when i pass the struct into Class B from Class A i can do this: //in classA.cpp
 .....
 .....
 B(..........., myStruct);

//in classB.cpp

B::B(........., data myStruct)
{
myStruct2(myStruct); //is this all it will take or do i need to also dynamicall allocate memory for the var *variables first before the struct copy?

}

//in classB.h
struct var
   {
    string name;
    string units;
    string value_type;
    string min;
    string max;
   };

   struct data
   {
    var *variables;
    int num_vars;
   };

   data myStruct2;

so since i want to make a copy and not send in a pointer does all this make sense. i really dont see a need to overide the = operator since i really wont be using it. once i have made that copy then i will not be need the struct from Class A anymore.

Share this post


Link to post
Share on other sites
Advertisement
#include <vector>

struct var
{
string name;
string units;
string value_type;
string min;
string max;
};

struct data
{
std::vector<var> variables;
};

data myStruct;

std::vector already has the copy constructor and assignment operator written for you. It also already manages memory allocation, reallocation, and deallocation. You can just pass around the data struct however you want; if you pass by value, or ever do an assignment, all the variables will get copied just as you want. You might even get rid of the data struct itself; just use a std::vector directly.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!