I am really have trouble understanding what I am doing wrong here. I have a child class that inherits protected items so that I can use them in the childs constructor.
1 2 3 4 5
class fiction
{
protected:
int ISBN;
float price;
1 2 3 4 5 6
class non_fiction
{
protected:
int copy_date;
int pages;
Then here is where I have a problem and I really don't get why since the items are inherited and are protected. Even is they were private it should pass them because in inheritance.
1 2 3 4
class library:non_fiction,fiction
{
public:
library(int n = 0, double p = 0.0, int w = 0, int z = 0):ISBN(n), price(p), copy_date(w), pages(z){}
initializer lists can only initialize members of THIS class (not of parent classes), this is because the parent classes are fully constructed (aside from the vtable) before the child class's ctor begins. Therefore you cannot call constructors for the members of the parent classes because they've already been constructed.
It also doesn't help that you're trying to init price (a float) with a double.
The solution here is to just move that stuff out of the initializer list:
1 2 3 4 5 6 7 8 9 10 11
class library : public non_fiction, public fiction // note, specify type of inheritance ftw
{
public:
library(int n = 0, float p = 0.0f, int w = 0, int z = 0)
{
ISBN = n;
price = p;
copy_date = w;
pages = z;
}
};
Or if you want to stick with initializer lists, make ctors for the parents:
1 2 3 4
library(int n = 0, float p = 0.0f, int w = 0, int z = 0)
: non_fiction(w,z), fiction(n,p)
{
}
your show_data function takes a fiction& f parameter, but your call f1.show_data() is not giving any paramenter.
You probably meant to have show_data be parameterless:
1 2 3 4 5
void show_data() // don't pass a fiction& reference.. just use 'this'
{
// note, no need for "f." here
cout << "International Standard Book Number " << ISBN << " Price " << price << endl;
}
Okay, I was mixing techniques there and didn't even realize it. Working off of pre-written code that I am supposed to use already existing main. Thank you for catching that. All done now. Thanks again!
A prime example of something that works (i.e. something that a compiler will pass and a computer will execute) but which could not be much more conceptually wrong.
How sad it is to see such a nice implementation tool like C++ being misused in this way.
I realise that you did not ask for opinions on your personal criteria for inheritance, but since the subject of this thread is 'inheritance', and your classification of objects looks like it is from another dimension...
A library is not a book.
A library does not need an ISBN, price, copy date or a number of pages.
An ISBN should be a string, not an integer.
Why would a book of fiction not have a copy date or a number of pages?
Why would a book of non-fiction not have an ISBN or a price?
Why don't you just specify a book class with an attribute 'Type' with domain {'Fiction', 'Non-fiction'}?