In this prblm I am to use dynamic mem allocation for both the base class and derived class
It compiles but crashes.
[code]//prblm #1 pg595 C++ Primer Plus Third Edition
#include <iostream>
using namespace std;
#include <stdlib.h>
#include "classich.h"
void Bravo(const Cd & disk);
int main()
{
Cd c1("Beatles", "Capitol", 14,35.5);
Classic c2=Classic("Piano Sonato in B flat , Fantaisia in C","Alfred Brendel","Philips",2,57.17);
Cd * pcd = &c1;
cout << "Using object directly:\n";
//************************** crashes here
pcd->Report(); // use CD method
pcd=&c2;
pcd->Report(); // use Classic method
cout << "Calling a function with a CD reference argument:\n";
Bravo(c1);
Bravo(c2);
cout << "Testing assignment: ";
Classic copy;
copy=c2;
copy.Report();
system("PAUSE");
return 0;
}
void Bravo(const Cd & disk)
{
disk.Report();
}
[\code]
here is the definiton file for my classes
Code:
//prblm #1 pg595 C++ Primer Plus Third Edition
#include <iostream>
using namespace std;
#include "classich.h"
Cd::Cd(char *s1,char * s2,int n,double x)
{
performers = new char[strlen(s1)+1];
label = new char[strlen(s2)+1];
strcpy(performers,s1);
strcpy(label,s2);
selection=n;
playtime=x;
}
Cd::Cd(const Cd & d)
{
performers = new char[strlen(d.performers)+1];
label = new char[strlen(d.label)+1];
strcpy(performers,d.performers);
strcpy(label,d.label);
selection=d.selection;
playtime=d.playtime;
}
Cd::Cd()
{
performers=new char[1];
label=new char[1];
performers[0]='\0';
label[0]='\0';
selection=0;
playtime=0;
}
Cd::~Cd()
{
delete [] performers;
delete [] label;
};
void Cd::Report()const
{
cout << "Performer:"<<performers<<endl;
cout << "label:"<<label<<endl;
cout << "Selection:"<<selection<<endl;
cout << "Playtime:"<<playtime<<endl;
}
Cd & Cd::operator=(const Cd & d)
{
if (this==&d)
return *this;
delete [] performers;
delete [] label;
performers=new char[strlen(d.performers)+1];
label=new char[strlen(d.label)+1];
strcpy(performers,d.performers);
strcpy(label,d.label);
selection=d.selection;
playtime=d.playtime;
return *this;
}
Classic::Classic(char * p,char * s1,char * s2,int n,double x) : Cd(s1,s2,n,x)
{
primary=new char[strlen(p)+1];
strcpy(primary,p);
}
Classic::Classic(const Classic & c):Cd(c)
{
primary=new char[strlen(c.primary)+1];
strcpy(primary,c.primary);
}
Classic::Classic()
{
primary=new char[1];
primary[0]='\0';
}
Classic::~Classic()
{
delete [] primary;
}
void Classic::Report() const
{
Cd::Report();
cout << "Primary work:"<<primary<<endl;
}
Classic & Classic::operator=(const Classic & c)
{
if (this==&c)
return *this;
Cd::operator=(c);
delete [] primary;
primary=new char[strlen(c.primary)+1];
strcpy(primary,c.primary);
return *this;
}
I can't spot the prblm please help!