c++ - std::vector segmentation fault during push_back -


i have class named book, contains books.

#ifndef book_h #include<string> #include<vector> #include<iostream> #define book_h class book { public:     std::string author, title;     int year;     book(){}     book(std::string author, std::string title, int year);     ~book(){}     void add_book();     std::vector<book*>library; };   #endif 

book.cpp file

#include "book.h"  book::book(std::string author, std::string title, int year) :author(author), title(title), year(year){}   void book::add_book() {     int y;     std::string a, t;     std::cin>>a;     std::cin>>t;     std::cin>>y;     library.push_back(new book(a, t, y)); } 

but when want add new book library, i'm getting segmentation fault during push_back of new object in main.cpp file

#include "book.h"  int main() {     book* ptr;     ptr->add_book();     return 0; } 

could explain me problem is?

i'm new in oop, , though i've read lot of posts here still can't find solution.

you don't initialise ptr in main;

int main() {     book* ptr = new book(); // initialize here     ptr->add_book();     return 0; } 

this fix segfault, however, i'm not sure of logic associated sample code, , possible memory leaks.


i separate library book type better composition , avoid heap allocation;

#include<string> #include<vector> #include<iostream>  class book { public:     std::string author, title;     int year;     book(){}     book(std::string author, std::string title, int year) : author(author), title(title), year(year) {}      ~book(){} };    struct library {     std::vector<book> books_;     void add_book(const book& value) { books_.push_back(value); } };  int main() {     library lib;     int y;     std::string a, t;     std::cin>>a;     std::cin>>t;     std::cin>>y;     lib.add_book(book(a, t, y));     return 0; } 

Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -