1

I am trying to understand the src code of FESVR in RISCV, I often come across using of class <class_name> inside a header file like the code linked below

https://github.com/riscv-software-src/riscv-isa-sim/blob/master/fesvr/elfloader.h

I know you can define a whole class inside a header file and include that header file inside a c++ file and use the object directly, but the code above does not completely define the class or create an object it just declares it.

Can anyone explain, what does declaring a class like this achieves?

  • What exactly are you referring to? Please reproduce the relevant part in the question. Are you referring to the line `class memif_t;`? That's just a forward-declaration of the class, declaring the name to be a class without defining it. Without the declaration `memif_t* memif` in the next line would give an error that `memif_t` is undeclared. – user17732522 Sep 15 '22 at 05:06

1 Answers1

1

It's called a forward declaration.

When you're only declaring functions, fields, etc., which use a reference or a pointer to a certain type, you don't necessarily have to know the complete type in order for the compiler to make sense of your code. It just needs to know that the type exists, you did not make any spelling mistakes, etc. E.g. at that point the type can be incomplete and a forward declaration is sufficient. This saves you from having to include the header file which declares the entire type, which saves compile time. Additionally it can break cyclic dependencies.

Only at the place where the type is actually used (in your case most likely in the .cpp file), the compiler must know whether the type actually has the fields or methods you're referring too, it must know the size of the type, etc.. E.g. the type must be complete at that point.

Use forward declarations wherever possible.

See:

Tohnmeister
  • 468
  • 1
  • 5
  • 14