I'm learning C++ and I have a some doubts about the deep copy, delete and assignment in this programming exercise; I've this simple hierarchy with an abstract base class:
class AudioFile{
private:
string title;
double size;
public:
AudioFile(string t, double d): title(t), size(d){}
virtual AudioFile * clone() = 0;
virtual bool quality() const = 0;
string getTitle() const{ return title;}
double getSize() const{ return size;}
virtual ~AudioFile(){}
};
class Mp3: public AudioFile{
private:
int bitRate;
public:
Mp3(string t, double d, int b): AudioFile(t,d), bitRate(b){}
virtual Mp3 * clone(){
Mp3 * t = new Mp3(getTitolo(),getDim(),bitRate);
return t;
}
virtual bool quality() const{
if(bitRate >= 192) return true;
else return false;
}
int getBitrate() const{ return bitRate;}
};
class WAV: public AudioFile{
private:
int freq; // in kHz
bool lossless;
public:
WAV(string t, double d, int f, bool l): AudioFile(t,d), freq(f), lossless(l){}
virtual WAV * clone(){
WAV * t = new WAV(getTitolo(),getDim(),freq,lossless);
return t;
}
virtual bool quality() const{
if(freq >= 96) return true;
else return false;
}
int getFreq() const{ return freq;}
bool isLossless() const{ return lossless;}
};
There's also a class called iZod
; its objects represent the tracks stored in a music player.
In iZod
class must be a nested class called Track
which represents a track contained in the player. Each Track
object has a polymorphic pointer to an AudioFile
.
Now I have these 4 questions:
Track
constructor must have this form:Track(AudioFile* f)
and has to build aTrack
object whose pointer has to point to a copy of of the object pointed byf
. Is my code right?I have to redefine the deep copy, deep assign and deep delete and I've done this way but I have some doubts:
deep copy, is that correct or have I to delete something?
deep assignment, is that correct?
deep delete; since in my two derived classes I've no pointers in data types, is it ok to only do the polymorphic-call
fa->~AudioAudio()
?
class iZod{
private:
class Track{
private:
AudioFile* fa;
public:
// CONSTRUCTOR
Track(AudioFile* f){
fa = f->clone();
}
// DEEP COPY
Track(const Track& b){
fa = b.fa->clone();
}
// DEEP ASSIGNMENT
Track& operator=(const Track& b){
if(this != &b){
fa->~AudioFile();
fa = b.fa->clone();
}
return *this;
}
// DEEP DELETE
~Track(){
fa->~AudioFile();
}
};
vector<Track> v;
public:
...
};