Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a C++ class without defining it in the current translation unit

Tags:

c++

class

It is possible to declare a class without defining it (forward declaration) as long as it is defined later on within the translation unit. In the case of functions, one can declare a function without defining it within the translation unit, and the linker will link it to its definition in a different translation unit. Is it possible to do the same with class declarations?

(if this is not possible, is there any use to a forwardly declared class without a definition in the current TL, or is that always an error?)

something like this, except this doesn't compile:

mymain.cpp:

class myclass; // declare without defining

myclass::myclass();
void myclass::barf();

int main() {
  myclass *m = new myclass();
  m->barf();
  return 0;
}

myclass.cpp:

#include <iostream>

class myclass { // define the implementation
public:
    myclass();
    void barf();
};

myclass::myclass() { } //empty constructor
void myclass::barf() {
    std::cout << "barfing\n";
}
like image 480
JanKanis Avatar asked Dec 16 '22 19:12

JanKanis


1 Answers

It is possible to forward-declare a class, but only pointers and references to forward-declared classes can be used. You can't use an actual object of a forward-declared class because the compiler doesn't know enough about it; in particular it doesn't know how large the object is or what its members are. Trying to forward-declare member functions (as you have done) won't work because the syntax of the forward declaration doesn't allow you to specify whether the functions are virtual or non-virtual (or perhaps inherited from some base class).

It is not often useful to forward-declare a class in a source file, but it can be useful in a header file. In particular it's common to forward-declare a class in a library's public header file and use pointers to that type as opaque handles. The class definition remains private to the library but user code can pass around pointers to objects of that class without ever knowing what the class's implementation looks like. This works particularly well when the pointers are smart pointers.

like image 53
dajames Avatar answered Jun 03 '23 08:06

dajames