Initialize struct in class constructor

10,761

Solution 1

 my_class() {
     s1 = new (my_struct);
     s1->i = 10;
     s1->name = (char *) malloc(strlen("anyname"));
     s1->name = "anyname";
     // here i want to make s1->i = 10; and s1->name = "anyname" ;  
     // should i assign it like s1->i= 10; and call new for s1->name and strcpy(s1->name "anyname");  
     // it compiles in g++ without any warning/error but gives seg fault at run time  
  }


 ~my_class(){
     free(s1->name);
     delete s1;
  }

Solution 2

I'm surprised that no-one has suggested the following...

struct my_struct
{
  int i; 
  std::string name;

  my_struct(int argI, std::string const& argName) : i(argI), name(argName) {}
};

class my_class
{
  my_struct s1;  // no need for pointers!

  my_class() : s1(1, std::string("test name")) {} // construct s1 using the two argument constructor, can also default construct as well.
};

With this approach, you don't need to worry about cleaning up s1, it's automatic...

Solution 3

When you create an instance of my_class, the s1 pointer doesn't point to anything. You have to allocate memory for it like so:

myclass() {
    s1 = new my_struct;
    // initialize variables
}

You will also have to create a destructor for it:

~myclass() {
    // delete variables
    delete s1;
}

Also, since this is C++, I recommend you use std::string instead of char*s.

Solution 4

Since this is C++, use std::string instead of char*:

struct my_struct{
    int i; 
    std::string name;
}; 
class my_class{ 
    my_struct* s1;
    my_class() {
        s1 = new my_struct;
        s1->i = 10;
        s1->name = "anyname";
    }
};

The reason your original code segfaulted was that you failed to allocate memory for s1 and also failed to allocate memory for s1->name. I've fixed the former with the new and the latter by using std::string. If for some reason you can't use std::string, use strdup where you were trying to use strcpy.

Lastly, don't forget to provide a destructor for my_class that'll delete s1 (and will free s1->name if you opt for char* and strdup).

Share:
10,761
Ruchi
Author by

Ruchi

Software Development Engineer

Updated on August 07, 2022

Comments

  • Ruchi
    Ruchi almost 2 years

    How can we initailize a struct pointer in constructor of a class. Example:

    struct my_struct{
        int i; 
        char* name;
    }; 
    class my_class{ 
        my_struct* s1;
        my_class() {
            // here i want to make s1->i = 10; and s1->name = "anyname" ;  
            // should i assign it like s1->i= 10; and call new for s1->name and strcpy(s1->name "anyname");  
            // it compiles in g++ without any warning/error but gives seg fault at run time  
        }
    };