"Has-a" relationship, Composition.

Apr 3, 2012 at 3:35am
I am a little unsure of "has-a" relationship between classes.

If I have:

1
2
3
4
5
6
7
8
9
class Library
{
private:
	int numCards;
	int numBooks;

	Book inbooks;
	Card incards;
//....  


Books constructor:
1
2
3
4
5
6
7
8
9
Book::Book(string &Title,string &Author,string &isbn, int &Status, int &Holder)
{
	title = Title;
	author = Author; 
	ISBN = isbn; 
	status = Status;
	holderID = Holder;
}


something like this maybe?
1
2
3
4
5
6
7
8
void Library::setinbooks(string a, string b, string c, int s, int h)
{
       inbooks.title = a;
       inbooks.author = b;
       inbooks.ISBN = c;
       inbooks.status = s; 
       inbooks.holderID = h;      
}


but theres no inheritance only composition?
can any one explain?
Apr 3, 2012 at 3:48am
any suggestions?
Apr 3, 2012 at 4:05am
A library has books, but a library is not a book. You use inheritance when you have an is a relationship. Library could for example, inherit a building class that contains member common to all buildings.
Apr 3, 2012 at 4:10am
Thank you, I have pretty good understanding of "Is-a" relationship (inheritance). Not so much about "has-a", I know you have to declare a class object inside a class, it "has" that object(parts) inside it.

I just need to know how I would define the above code.

Apr 3, 2012 at 4:18am
Your library class should have a container like a vector to hold the books and one for cards, right now you have only one book and one card. You can then have a member function in library to add books.
Apr 3, 2012 at 5:34am
Library does have a vector for Books and Cards, just didn't show it here, it also has a member function to add Books/Cards.

a little info on the project:
I am reading from .txt files Book and Card, reading them into vectors (also trying with objects), when user adds new book/card it writes back to .txt files and updates them.

Library has another member function showbooks(),
1
2
3
4
5
6
7
8
9
void Library::showBooks()
{
	for(int i=0; i!= booklist.size(); i++)
	{
		booklist[i].printbooks();
	}
        //OR
       // inbooks[numBooks].printbooks();
}

But nothing shows!! and i've been trying for a long time different things and it is due soon.
I figured I don't have the
Book inbooks
defined, and I don't know how to.

Any help will be really appreciated!
Topic archived. No new replies allowed.