LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C++ class inside struct (https://www.linuxquestions.org/questions/programming-9/c-class-inside-struct-873879/)

wagaboy 04-08-2011 07:51 PM

C++ class inside struct
 
Is is possible to use a class inside a struct ? I keep getting segmentation fault with this code:

Code:

struct my_struct {
    unsigned count;
    std::string msg;
};

int main () {
    ...
  my_struct* temp = (my_struct*) malloc(sizeof(my_struct));
  cin >> temp->count; // Works fine
  cin >> temp->msg; // Segmentation fault :(
    ...
}


paulsm4 04-08-2011 09:47 PM

Hi -

Quote:

Q: Is is possible to use a class inside a struct?
Sure. Just don't "malloc()" a class ;)

Declare it in-line, or use "new".

wagaboy 04-08-2011 11:58 PM

paulsm4, thank you. I thought I could use malloc since it was a struct, but as you said struct is also a class.

johnsfine 04-09-2011 07:39 AM

Quote:

Originally Posted by wagaboy (Post 4318762)
I thought I could use malloc since it was a struct, but as you said struct is also a class.

You could use malloc correctly on a class or struct if that class or struct did not need its constructor to be called. That doesn't mean you should use malloc in that case. I'd still use new.

In your example, what matters is the fact that std::string has a default construct and a std:string requires initialization by one of its constructors.

Your struct has no source code for constructors, but every member either has a default constructor or doesn't have any constructor, and at least one member has a default constructor. That all causes the compiler to provide default constructor for your struct. Using new causes the constructor to be used. Using malloc bypasses the constructor.


All times are GMT -5. The time now is 05:39 AM.