Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward Declaration of variables/classes in std namespace

I usually use forward declaration predominantly, if I have a class that does not need complete definition in .hpp file

Ex)

 //B.hpp

 namespace A_file {
   class A;
 }

 namespace B_file {

  class B {
   public:
        B();
   private:
        A *ptr_to_A;
  }
 }

 //B.cpp

 #include "A.hpp"
 using namespace A_file;

 namespace B_file {

   B(int value_) {
        *ptr_to_A = new A(value_);
   }

   int some_func() {
        ptr_to_A->some_func_in_A();
   }
 }

I write this kind of code. I think, it will save including the whole hpp again. (Feel free to comment, if you thing, this is not healthy)

Is there a way that I can do the same for objects/classes in std namespace? If there is a way, is it okay or does it have side effects?

like image 319
howtechstuffworks Avatar asked Apr 23 '12 23:04

howtechstuffworks


People also ask

What is the forward declaration of classes?

Forward Declaration refers to the beforehand declaration of the syntax or signature of an identifier, variable, function, class, etc. prior to its usage (done later in the program). In C++, Forward declarations are usually used for Classes.

How do you forward a declaration?

To write a forward declaration for a function, we use a function declaration statement (also called a function prototype). The function declaration consists of the function header (the function's return type, name, and parameter types), terminated with a semicolon. The function body is not included in the declaration.

What is forward declaration in programming?

In computer programming, a forward declaration is a declaration of an identifier (denoting an entity such as a type, a variable, a constant, or a function) for which the programmer has not yet given a complete definition.

What is forward declaration in Oracle?

This declaration makes that program available to be called by other programs even before the program definition. Remember that both procedures and functions have a header and a body. A forward declaration consists simply of the program header followed by a semicolon (;). This construction is called the module header.


1 Answers

You can forward declare your own classes in header files to save compilation time. But you can't for classes in namespace std. According to the C++11 standard, 17.6.4.2.1:

The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified.

Note that some of these classes are typedefs of templated classes, so a simple forward declaration will not work. You can use #include<iosfwd> instead of #include<iostream> for example, but there are no similar headers with just forward declarations for string, vector, etc.

See GotW #34, Forward Declarations for more information.

like image 96
JohnPS Avatar answered Oct 21 '22 08:10

JohnPS