-2

i want to access methods and fields from class Product in class Menu. So i write the following code:

Menu.h

#include "Product.h"
class Menu{
public:
  Menu(Product& prod);
  Menu();
private:
  Product product;}

Menu.cpp

 #include "Menu.h"
 Menu::Menu(Product& prod) { this->product = prod; }
 Menu::Menu() {}

Product.h

 #include "Menu.h"
 Class Product{
 public:
    Product():
}

and i get the following error in Menu constructor: syntax error: identifier 'Product'.

i changed Menu constructor to:

Menu(const Product& prod)

but it didn't work too.

Anyone know how to solve it?

Stefan
  • 17,448
  • 11
  • 60
  • 79

2 Answers2

0

remove #include "Menu.h" from Product.h

and yes, please provide a full example.

  • If there are header guards, surely that doesnt make a difference. – Samer Tufail Oct 18 '17 at 09:49
  • 1
    @SamerTufail Did you see any header guards in the example shown? – Algirdas Preidžius Oct 18 '17 at 09:54
  • @AlgirdasPreidžius usually they are auto generated and when posting examples, usually they are not added. Point being I would wait for [mcve] – Samer Tufail Oct 18 '17 at 09:57
  • @SamerTufail No, header guards won't help circular dependency. – songyuanyao Oct 18 '17 at 09:57
  • @songyuanyao They do otherwise the guards are pointless https://en.wikipedia.org/wiki/Include_guard and ofcourse https://stackoverflow.com/questions/3127171/how-are-circular-includes-resolved – Samer Tufail Oct 18 '17 at 10:01
  • 1
    @SamerTufail Auto generated, by what? If they are auto generated by your tool of choice, it doesn't mean that they are, by whatever OP is using. – Algirdas Preidžius Oct 18 '17 at 10:08
  • 4
    @SamerTufail you are mistaken. Include guards protect against multiple inclusion, not against circular dependencies. There is no way to resolve curcular dependencies mechanically. – n. m. could be an AI Oct 18 '17 at 10:13
  • @n.m. agreed, this is a case of multiple inclusion camaflouged under the term 'circular dependency' - the orginal solution above need not be if guards are used or #pragma once. Circular dependency between classes and multiple inclusion of the same header file are seperate issues. – Samer Tufail Oct 18 '17 at 10:17
0

After cleaning up your code from the errors, it looks like this and compiles like a charm:

Menu.h

#include "Product.h"

class Menu {
public:
    Menu(Product& prod);
    Menu();
private:
    Product product;
};

Menu.cpp

#include "Menu.h"

Menu::Menu(Product& prod)
{
    product = prod;
}

Menu::Menu()
{

}

Product.h

class Product {
public:
    Product()
    {

    }
};
scopchanov
  • 7,966
  • 10
  • 40
  • 68