Forward declaration (Forward declaration)

Source: Internet
Author: User
Forward declarations in C + +

A forward declaration is an incomplete type declaration, so he cannot replace the complete type, and for the compiler, the forward declaration is not available when it is necessary to know the size and content of the object being declared. So its application scenario is limited to the following: 1, declaring references and pointer 2, as functions (declaration only), return type or parameter type.

Here's an application scenario:
A.h

#ifndef __a__h__
#define __A__H__

#include <string>
class B;  This is the forward declaration

class A {public
:
  B getbfroma ();
  std::string who_are_you ();

};
#endif

B.h

#ifndef __b__h__
#define __B__H__

#include <string>

class A;  This is the forward declaration

class B {public
:
  A Getafromb ();
  std::string who_are_you ();
};

#endif

A.cpp

#include "A.h"
#include "B.h"

B a::getbfroma () {return
  B ();
}

std::string a::who_are_you () {return
  "I am A";
}

B.cpp

#include "B.h"
#include "A.h"

a B::getafromb () {return
  a ();
}
std::string b::who_are_you () {return
  "I am B";
}

Main.cpp

#include "A.h"
#include "B.h"

#include <iostream>

int main () {
  A;
  b b;

  A ab = B.getafromb ();
  B ba = A.getbfroma ();

  Std::cout << "AB is:" << ab.who_are_you () << Endl;
  Std::cout << "BA is:" << ba.who_are_you () << Endl;

  return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.