0

I recently started learning C++.

I would like to know why it is not possible to define a variable in a header file like this :

#ifndef DUMMY_H
#define DUMMY_H


class Dummy
{
stack<std::pair<int, int>> s;   

};


#endif //DUMMY_H
jiji
  • 337
  • 2
  • 3
  • 13

2 Answers2

4

You are missing:

  • a #include <stack> statement, so the compiler knows what stack is (and a #include <utility> statement for std::pair).

  • a using namespace std; or using std::stack; statement, so you can use std::stack without specifying the std:: prefix.

Try this:

#ifndef DUMMY_H
#define DUMMY_H

#include <stack>
#include <utility>

using std::stack;

class Dummy
{
    stack<std::pair<int, int>> s;   
};

#endif //DUMMY_H

You really shouldn't use a using statement in a header file *, unless it is nested inside of an explicit namespace:

#ifndef DUMMY_H
#define DUMMY_H

#include <stack>
#include <utility>

class Dummy
{
    std::stack<std::pair<int, int>> s;   
};

#endif //DUMMY_H

* using a type/namespace into the global namespace can cause undesirable side effects if you are not careful!

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
1

You must include required header before using them. Also precaution has to be taken care to add appropriate namespace resolution.

#ifndef DUMMY_H
#define DUMMY_H

#include <stack>
#include <utility>  // This has added for pair

class Dummy
{
    std::stack<std::pair<int, int> > s;  // Notice the space between > >.
};

#endif //DUMMY_H

Additional space is required in earlier version of C++98 for grammatical reason. More information: Template within template: why "`>>' should be `> >' within a nested template argument list"

This is not required from C++03

sameer chaudhari
  • 928
  • 7
  • 14