Program received signal SIGSEGV, Segmentation fault.
0x001c74a5 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&) () from /usr/lib/libstdc++.so.6
(gdb) where
#0 0x001c74a5 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&) () from /usr/lib/libstdc++.so.6
#1 0x0804b444 in Time::getTOD (this=0x0) at Time.cpp:63
#2 0x0804a4f0 in main (argc=2, argv=0xbffff7a4) at printsongs.cpp:102
(gdb) frame 1
#1 0x0804b444 in Time::getTOD (this=0x0) at Time.cpp:63
63 return timeofday;
(gdb) frame 2
#2 0x0804a4f0 in main (argc=2, argv=0xbffff7a4) at printsongs.cpp:102
102 << T->getMinute() << " " << T->getTOD() << endl;
(gdb)

Here are the codes:

Song s = songs.getNthSong (n);
Song defaultSong;

// Print out the last time it was played
if (!(s == defaultSong) ) {
Time *T = s.getLastPlayed();
cout << "Song #" << n << " is " << s.getTitle() << " by "
<< s.getArtist() << ". Last played at " << T->getHour() << ":"
<< T->getMinute() << " " << T->getTOD() << endl;
}


string Time::getTOD()
{
return timeofday;
}

This error happens when I add the operator= method

Song& Song::operator =(const Song &so){


if(last_played==0){
last_played=0;
}
else{
if(last_played!=0){
delete last_played;
}
last_played=new Time (*so.getLastPlayed());
}
artist=so.getArtist();
title=so.getTitle();


}

Recommended Answers

All 4 Replies

for which code statement you have overloaded operator= ?

can you also share the song class.

newbieha, you see the button that says CODE? You should click that and paste your code within those tags. And like stated above, a peek at the song class would help significantly with.

I am unable to understand your code

Song& Song::operator =(const Song &so){
if(last_played==0){
last_played=0;
}
else{
if(last_played!=0){
delete last_played;
}
last_played=new Time (*so.getLastPlayed()); // You are using so as reference(const Song &so) then why you are trying to call with "*" . This call should be  so.getLastPlayed()
}
artist=so.getArtist();
title=so.getTitle();


}

I am unable to understand your code

last_played=new Time (*so.getLastPlayed()); // You are using so as reference(const Song &so) then why you are trying to call with "*" . This call should be  so.getLastPlayed()

the .-operator (element-of-object) has a higher precedence than the *-operator (dereference-pointer), so the OP's code is equivalent to:

last_played = new Time (*(so.getLastPlayed()));

The problem might be that so.getLastPlayed() is returning a NULL pointer. In that case, what should this->last_played be set to? And why is it returning a pointer in the first place? If it returns a const Time & instead, then we don't have this problem....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.