I have been learning on classes in c++ and I got a certain code from an old russian book its about a book class, I tried modifying it and running it its not working may some help me understanding why the authour used this code(what does strdup do?)
Author = strdup(autho);
inside the constructor and was wrong with this line of code
Book s("edgar", "science", "chemistry for dummies", "502","12.11.13","1.12.96");
Anyone with a simple straight explanation?
Main code below
using namespace std;
class Book{
char * Author;
char * Type;
char * Title;
int * Pages;
unsigned int * Yearpublished;
unsigned int * Publishing;
Book(char * autho, char * type, char * title, int * pages, unsigned int * yearpublished, unsigned int * publishing ){
Author = strdup(autho);
Type = strdup(type);
Title = strdup(title);
Pages = pages;
Yearpublished = yearpublished;
Publishing = publishing;
}
~Book(){
if(Author != NULL){
free(Author);
}
if(Type != NULL){
free(Type);
}
if(Title != NULL){
free(Title);
}
}
};
int main(){
cout << "main start" << endl;
Book s("edgar", "science", "chemistry for dummies", "502","12.11.13","1.12.96");
cout << "main finish" << endl;
return 0;
}
There are many, many things wrong with the code posted. So many things that virtually every single line is in error.
One of the most obvious is that you’re trying to store a year as an
int *, and then passing in a string containing"12.11.13". That doesn’t work. You’re doing the same forpages; accepting anint*and passing in a string containing an int. You can’t do that, that isn’t how pointers work. Most of your usage of pointers indicates that you don’t really know what the*does, and you should stop and read about pointers before you introduce some very difficult to track down bugs into your code. You should either store your year as a string (very bad idea) or store it as an integer in unix time, which is pretty standard.You should remove
using namespace stdand replace it with#include <string>. You should throw out all the lines that start withchar*, and replace them withstd::stringand throw out yourint*lines and make themint.You’re also declaring a private constructor and destructor. You need to add
public:after the member variable declarations but beforeBook(). Then you should throw out the body of your constructor and use initializer lists.You’re also not including
<iostream>, so yourcoutcalls are probably causing errors.Once you’ve done the above, you should remove the destructor
~Book()completely.For example: