1
votes

I am learning c++ inheritance and here I have a problem. if I make this simple code all in main.cpp file it will works without any problem.

but when I seperate the files in header file and else it won't work and it gives me some errors.

here is the code of header file named book.h

 #ifndef BOOK_H
 #define BOOK_H

 class book
{
 private:
 string name;

 public:
 book(string n = "default") : name(n) {};
 ~book() {};
 void printname();
};

#endif

and here is the code of book.cpp that I defined the function of this class in this file.

#include <iostream>
#include <Windows.h>
#include <string>
#include "book.h"

using namespace std;

void book::printname()
{
 cout << name << endl;
 return;
}

and finally the main.cpp file:

#include <iostream>
#include <Windows.h> 
#include <string>
#include "book.h"

using namespace std;

 int main()
{
 system("color 0A");
 book programing("c++");
 cout << "the name of the book is ";
 programing.printname();

 system("pause");
 return;
}

and the errors that I get:

Severity Code Description Project File Line Suppression State

Error C2065 'name': undeclared identifier book d:\vs program\book\book\book.cpp 10

Error C3646 'name': unknown override specifier book d:\vs program\book\book\book.h 7

Error C4430 missing type specifier - int assumed. Note: C++ does not support default-int book d:\vs program\book\book\book.h 7

Error C2061 syntax error: identifier 'string' book d:\vs program\book\book\book.h 10

Error C2065 'n': undeclared identifier book d:\vs program\book\book\book.h 10

Error C2614 'book': illegal member initialization: 'name' is not a base or member book d:\vs program\book\book\book.h 10

Error C3646 'name': unknown override specifier book d:\vs program\book\book\book.h 7

Error C4430 missing type specifier - int assumed. Note: C++ does not support default-int book d:\vs program\book\book\book.h 7
Error C2061 syntax error: identifier 'string' book d:\vs program\book\book\book.h 10

Error C2065 'n': undeclared identifier book d:\vs program\book\book\book.h 10

Error C2614 'book': illegal member initialization: 'name' is not a base or member book d:\vs program\book\book\book.h 10

and other errors...

2

2 Answers

7
votes

You need to make sure that string is a valid type in the .h file.

  1. Add #include <string>.
  2. Use std::string instead of just string.

#ifndef BOOK_H
#define BOOK_H

#include <string>

class book
{
   private:
      std::string name;

   public:
      book(std::string n = "default") : name(n) {};
      ~book() {};
      void printname();
};

#endif
1
votes

This answer appears to address your question. As a side note, since C++11, you can also specify default values for class members. So you could just do this instead:

#ifndef BOOK_H
#define BOOK_H

#include <string>

class book
{
   private:
      std::string name = "default";

   public:
      book() = default;
      book(std::string n) : name(n) {};
      ~book() {};
      void printname();
};

#endif