Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference between #include .h and just stating class A; in C++ [duplicate]

Tags:

c++

class

header

I'm analying an Operating Systems project for school and came across this header file:

//kernelev.h

#ifndef _KERNELEV_H 
#define _EVENT_H_

typedef unsigned char IVTNo;

class Thread;
class PCB;
class KernelSem;

class KernelEv {
public:
     KernelEv (IVTNo ivtNo);
     ~KernelEv();
     int wait(int MaxTimeToWait);
     void signal();

[...]

Now, when writing the complete definitions of these methods (KernelEv, ~KernelEv, wait and signal), they used the attributes of the classes Thread, PCB and KernelSem. What would be the difference between generally introducing for instance #include Thread.h; #include KernelSem.h; and just declaring the classes like this: class Thread; Are there differences in data access rights? Or it's somehow completely different?

Thanks for your help, I hope my question is clear enough.

like image 420
Stefan Wœlfisch Avatar asked Sep 18 '25 00:09

Stefan Wœlfisch


2 Answers

First, note that if you only introduce the classes, you won't be able to use the methods;

class Thread;

Thread x; // compile error: size of x unknown
Thread* x; // this is ok
// set x to some valid thread, maybe as a parameter
x->signal(); // compile error

But it makes no difference whether your declarations are in a header or included in your file. That is, you could replace the include line with a copy of the header and everything would work perfectly fine (every line in the above example would be valid). There are many reasons not to, however. Ease of maintenance would be the top issue, along with readability and modularity. It would also be less applicable to compiler caching (so would generally take longer to compile)

like image 55
Dave Avatar answered Sep 20 '25 15:09

Dave


If you only have a declaration class A; and not the full class definition, then the type is said to be incomplete. This can be used in limited ways; you can do things that only need knowledge that the class exists, for example:

  • Declare a pointer or reference to it;
  • Declare a function using it as a parameter or return type;
  • Declare (but not define) an external variable of that type.

You can't do anything that requires knowledge of the class members, size, or other details given by the definition, for example:

  • Define a variable of that type;
  • Define a function using it;
  • Access any members or nested declarations;
  • Inherit from it;
  • Apply sizeof to it.
like image 25
Mike Seymour Avatar answered Sep 20 '25 16:09

Mike Seymour