Home > Back-end >  Destructor not finding my namespace method
Destructor not finding my namespace method

Time:12-30

main.cpp:

#include "headerone.hpp"

int main() {
    menus::menu();
}

headerone.hpp:

#pragma once

#include "headertwo.hpp"

namespace menus {
    void menu() {
       object instance;
    }
}

headertwo.hpp:

#pragma once

#include "headerone.hpp"

class object {
public:
    object() {
       method();
    }

    void method() {
        int x; /* do something */
    }

    ~object() {
        menus::menu();
    }
};

I get an error in the deconstructor saying that menu namespace cannot be found.

Error C2653 'menu': is not a class or namespace name

CodePudding user response:

The menu() function should only be declared in the header file. The definition should be in its associated .cpp source file.

The headerone.hpp file should look like this:

#pragma once

namespace menus {

void menu();

} // menus

The headerone.cpp file should look like this:

#include "headerone.hpp"
#include "headertwo.hpp"

namespace menus {

void menu() {
   object instance;
}

} // menus

One of the areas that many good C books omit are how source files, header files, and projects should be put together. There is one good — albeit rather long in the tooth (but still relevant) — book called Large-Scale C Software Design by John Lakos which discusses project layout and suggested implementation in great detail.

He also has a more recent book in two volumes called Large-Scale C , which is not a replacement for the earlier book. Rather it has an even broader and more ambitious scope for software development. Volume I is Process and Architecture, and Volume II is Design and Implementation.

CodePudding user response:

You have cyclic dependency in your program.

You can solve this by using source files(.cpp) in addition to header files(.hpp) as shown below:

headerone.hpp

#pragma once

#include "headertwo.hpp"

namespace menus {
    void menu(); //this is a declaration
}

headerone.cpp

#include "headerone.hpp"
namespace menus
{
//this is a definition
void menu() {
       object instance;
}
}

headertwo.hpp

#pragma once

//no need to include headerone.hpp here

class object {
public:
    object() {
       method();
    }

    void method() {
        int x; /* do something */
    }

    ~object();//this is a declaration
};

headertwo.cpp

#include "headertwo.hpp"
#include "headerone.hpp"
object::~object() {
        menus::menu();
}

main.cpp

#include "headerone.hpp"
#include "headertwo.hpp"
int main() {
    menus::menu();
}

The output of the above modified program can be seen here.

  •  Tags:  
  • c
  • Related