CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jun 2015
    Posts
    21

    How can we move implementation to multiple header file without circularity?

    for single .cpp file- and .h file- we can move implementation from .cpp to .h file, but for multiple files, i can not do this for my case and occurred circularity :
    my case is something like this (inclusion guard ignored):

    //a.h

    #include"stdio.h"
    #include"b.h"

    class A
    {
    public:
    void showfromA(const B& b);
    int index;
    };

    //a.cpp

    #include"a.h"
    void A::showfromA(const B& b)
    {
    printf("b.index=%i",b.index);
    }

    //b.h

    class B
    {
    public:
    void showfromB();
    int index;
    };

    //b.cpp

    #include"a.h"
    void B::showfromB()
    {
    A a;
    a.index=1;
    printf("a.index=%i",a.index);
    }

    //main.cpp

    #include"b.h"
    main()
    {
    B b;
    b.showfromB();
    }
    circularity occurred because a.h include b.h but b.cpp include a.h.
    **when .h files and .cpp files are separated ,the code is OK** and we do not have circularity but when we try to merge .h file and .cpp file we encounter to circularity between class A and B and compile error. note that i want to move method implantation from .cpp file into * the class definition* in .h file.
    Last edited by alwaystudent; June 11th, 2015 at 08:13 PM. Reason: misspelling

  2. #2
    Join Date
    Jun 2015
    Posts
    208

    Re: How can we move implementation to multiple header file without circularity?

    Quote Originally Posted by alwaystudent View Post
    circularity occurred because a.h include b.h but b.cpp include a.h.
    Since A and B are mutually dependent and always appear together anyway why not define them on the same include file? Then the dependency issue can (usually) be resolved by the use of forward declarations.

    But the deeper problem is that A and B are mutually dependent in the first place. This is a design issue called tight coupling. To fix it, in principle the dependency between A and B (the reason why they cling to each other) is broken out and put in a new class C which is independent of A and B (this may require the use of inheritance, that is A and B inherit C). Now A and B are both dependent on C but no longer on each other. The tight coupling between A and B has been loosened and there is no circularity in the definitions anymore.
    Last edited by tiliavirga; June 12th, 2015 at 12:29 AM.

  3. #3
    Join Date
    Jun 2015
    Posts
    21

    Re: How can we move implementation to multiple header file without circularity?

    @tiliavirga Thanks for your brilliant idea,

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured