Abstract class

well this is my code. i need to create a vector of pointers and hold the book objects in it. then i have a virtual function in my books which is a pure virtual in LibraryItems.when i try to add the books object in my code, i understand that since the scope runs out there is no object that is added. so when i run print it gives me an error. cant figure out

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include<iostream>
#include "books.h"
#include "library.h"
#include <vector>
using namespace std;



int main(int argc, char * argv[])
{
	vector<LibraryItems* >libraryInfo;
	string book, author;
	int rCode;
	int i = 0;
	while(i < 3)
	{
		cout << "\nEnter the name of the Book:";		
		cin >> book;		
		cout << "\nEnter the refCode:";		
		cin >> rCode;
		cout << "\nEnter the name of the author:";
		cin >>author;
		Books b1(book, rCode, author);
		libraryInfo.push_back(&b1);
		i++;
	}
	for(int i = 0; i < libraryInfo.size(); ++i)
	{
		libraryInfo[i] -> print();	
	}
	system("pause");
	return 0;
}


You should create your objects in heap instead of stack.
Note that you will run into memory leak issue or ugly manual management with vector of raw pointers.
Use unique_ptr instead (or shared_ptr if you need an shared ownership)
Could you give me an example
1
2
3
4
5
#include <memory>
//...
vector<std::unique_ptr<LibraryItems>> libraryInfo;
//...
libraryInfo.emplace_back(new Books(book, rCode, author));
If you do not want to use smart pointers (which you should), you can use normal pointers instead and manage all removal manually.
Alright thanks.
Topic archived. No new replies allowed.