Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Going from Java imports to C++ includes

Tags:

java

c++

class

I've been struggling with understanding how C++ classes include other classes. I'm guessing this is easier to understand without any preconceived notions.

Assume my two classes are Library and Book. I have a .h and .cpp file for each. My "main.cpp" runs a simple console app to use them. Here is a simple example:

//Library.h

#ifndef LIBRARY_H_
#define LIBRARY_H_
#endif

class Library
{

public:
 Library();
 ~ Library();

private:
 Book *database;
};

This throws an error about how "Book does not name a type". In Java I would import some package like org.me.Domain.Book. Can someone please explain how this works in C++?

like image 329
Stephano Avatar asked Dec 13 '22 23:12

Stephano


1 Answers

In C++ source files are conceptually completely separate from class definitions.

#include and header files work at a basic text level. #include "myfile" simply includes the contents of the file myfile at the point at which the include directive is placed.

Only after this process has happened is the resulting block of text interpreted as C++ code. There is no language requirement that a class called Book has to be defined in a file called Book.h. Although it is highly recommended that you do follow such a convention, it's essential to remember that it's not a given when debugging missing declaration or definition issues.

When parsing your Library.h file the compiler must have seen a declaration for the identifier Book at the point at which it is used in the defintion of the class Library.

As you are only declaring a member variable of type "pointer to Book", you only need a declaration and not a full definition to be available so if Book is a class then the simplest 'fix' is to add a forward declaration for it before the definition of Library.

e.g.

class Book;

class Library
{
    // definition as before
};

Include Guards

It looks like you may have some include guard errors. Because you can only define classes once per translation units the definitions inside header files are usually protected with include guards. These ensure that if the same header is included multiple times via different include files that the definitions it provides aren't seen more than once. Include guards should be arranged something like this. Looking at your Library.h, it may be that your include guards are not terminated correctly.

myclass.h:

#ifndef MYCLASS_H
#define MYCLASS_H

class MyClass
{
};

// The #ifndef is terminated after all defintions in this header file
#endif //MYCLASS_H
like image 169
CB Bailey Avatar answered Dec 15 '22 12:12

CB Bailey