Reputation: 361
The beginning of my class is:
class Player{
private:
Cardpile hand;
...
}
Where Cardpile is another class. If I do Player *p=new Player();
Is hand automatically initialized? I am asking this because I been trying to figure out a segmentation fault. I have looked everywhere in my code. The last thing I can think of is that hand
is not initialized.
EDIT: This is the segmentation error I got. Card is a class inside of Cardpile. I know Card and Cardpile both works.
Program received signal SIGSEGV, Segmentation fault.
0x0000000000402ac0 in __gnu_cxx::new_allocator<Card*>::construct (this=0x6070a8, __p=0x4015c6, __val=@0x7fffffffe6d8) at /usr/include/c++/4.4/ext/new_allocator.h:105
105 { ::new((void *)__p) _Tp(__val); }
EDIT: Cardpile class:
class Cardpile : private vector<Card*> {
public:
using vector<Card*>::size;
using vector<Card*>::at;
Cardpile ();
...
}
Cardpile::Cardpile(){}
EDIT: Here is a cool fact: p==NULL does not check if p is initiated. I guess that's why I keep getting segmentation fault.
Upvotes: 4
Views: 172
Reputation: 74058
If you don't explicitly member initialize hand
in your Player
constructor, then the default constructor of Cardpile
will be used.
If you haven't defined a default constructor, the compiler will create one.
When you compile and link your program with -g
, gdb can show the stacktrace where your program crashed:
gdb program core
and then inside gdb enter bt
. This will show the complete call stack at time of the segmentation fault.
Upvotes: 3
Reputation: 258618
It depends on what Cardpile
is. If it's a POD, then no:
class Cardpile1{
int x;
};
If it's not, then yes:
class Cardpile2{
Cardpile2() : x(0) {}
int x;
};
hand
will exist for both cases, but reading from it is illegal if Cardpile
is defined as a POD.
class Player{
public:
Cardpile1 hand1;
Cardpile2 hand2;
};
Player p;
p.hand1.x; //illegal
p.hand2.x; //legal
Upvotes: 3