classic.h
// base class
// #pragma once
#ifndef CLASSIC_H_
#define CLASSIC_H_
class Cd { // represents a CD disk
private:
char performers[50];
char label[20];
int selections; // number of selections
double playtime; // playing time in minutes
public:
Cd(char * s1 = "", char * s2 = "", int n = 0, double x = 0.0);
Cd(const Cd & d);
~Cd();
virtual void Report() const; // reports all CD data
Cd & operator=(const Cd & d);
};
class Classic :public Cd
{
private:
char songs[80];
public:
Classic(const char * sg = "", char * s1 = "", char * s2 = "", int n = 0, double x = 0.0);
~Classic();
virtual void Report() const;
Classic & operator=(const Classic &cl);
};
#endif // !CLASSIC_H_
classic.cpp
#include "classic.h"
#include <iostream>
Cd::Cd(char * s1, char * s2, int n, double x)
{
std::strncpy(performers, s1, 50);
std::strncpy(label, s2, 20);
selections = n;
playtime = x;
}
Cd::Cd(const Cd & d)
{
std::strncpy(performers, d.performers, 50);
std::strncpy(label, d.label, 20);
selections = d.selections;
playtime = d.playtime;
}
Cd::~Cd()
{
}
void Cd::Report() const
{
std::cout << "Performers: " << performers << std::endl;
std::cout << "Label: " << label << std::endl;
std::cout << "Selections: " << selections << std::endl;
std::cout << "Playtime: " << playtime << std::endl;
}
Cd & Cd::operator=(const Cd & d)
{
if (this == &d)
return *this;
std::strncpy(performers, d.performers, 50);
std::strncpy(label, d.label, 20);
selections = d.selections;
playtime = d.playtime;
return *this;
}
Classic::Classic(const char * sg, char * s1, char * s2, int n, double x) :Cd(s1, s2, n, x)
{
std::strncpy(songs, sg, 80);
}
Classic::~Classic()
{
}
void Classic::Report() const
{
Cd::Report();
std::cout << "Songs: " << songs << std::endl;
}
Classic & Classic::operator=(const Classic & cl)
{
if (this == &cl)
return *this;
Cd::operator=(cl);
std::strncpy(songs, cl.songs, 80);
return *this;
}
main.cpp
#include <iostream>
using namespace std;
#include "classic.h" // which will contain #include cd.h
void Bravo(const Cd & disk);
int main()
{
Cd cl("Beatles", "CapitoPV", 14, 35.5);
Classic c2 = Classic("Piano Sonata in-B flat, Fantasia in-C",
"Alfred Brendel", "Philips", 2, 57.17);
Cd *pcd = &cl;
cout << "Using obfectr directly:\n";
cl.Report(); // use Cd method
c2.Report(); // use Classic method
cout << "Using type cd * pointer to objects:\n";
pcd->Report(); // use Cd method for cd object
pcd = &c2;
pcd->Report(); // use Classic method for classic object
cout << "Calling, a function with a Cd reference argument:\n";
Bravo(cl);
Bravo(c2);
cout << "Testing assignment: ";
Classic copy;
copy = c2;
copy.Report();
cin.get();
return 0;
}
void Bravo(const Cd & disk)
{
disk.Report();
}