0

Can I create an object of a class in the same class ? If not what can I do ?

example stack class

template <class T>
class stack
{

void push(T d)
{
...
}

T pop()
{
...
}

//my question is about this one
void sort()
{
// I get errors when I do that ?
 stack st;
 st.push(4);
}

};
fvu
  • 32,488
  • 6
  • 61
  • 79
user2849898
  • 1
  • 1
  • 2

2 Answers2

1

Without templates this is fine, e.g.

class stack
{
  public: //<-- added so we can use this
  void push(int d)
  {
  //...
  }

  int pop()
  {
  //...
  }

  void sort()
  {
    stack st;
    st.push(4);
  }
};

Now, in your templated case, you will need to can tell the sort function what kind of stack to make.

  void sort()
  {
    stack<T> st;
    //---^^^
    st.push(4);
  }

more edit Section 14.6.1

"The injected-class-name can be used with or without a template-argument-list. When it is used without a template-argument-list, it is equivalent to the injected-class-name followed by the template-parameters of the class template enclosed in <>."

So, you can say stack st;
You will not be able to have a member variable of type stack<T> though.

doctorlove
  • 18,872
  • 2
  • 46
  • 62
0

It's perfectly OK to create an object of the same type inside a class. You should be able to get it to work with stack<T>, like this

template <class T>
class stack
{
    ...

    void sort()
    {
        stack<T> st;
        st.push(4);
    }

    ...
};

It seems that stack st; is correct according to the latest C++ standards, but maybe your compiler hasn't implemented this part of the C++ standard yet.

Having said that, it's not clear from your posted code why this is a template. If it were a template I'd expect to see

void push(const T& x)
{
    ...
}

T pop()
{
    ...
}

etc. Are you sure you want this to be a template? You should do that properly or not at all.

john
  • 85,011
  • 4
  • 57
  • 81
  • I'm wondering how the sort is going to try to swap itself with `st` – doctorlove Oct 07 '13 at 12:32
  • I think Section 14.6.1 means we are wrong, and it compiles ok without on VS2012. – doctorlove Oct 07 '13 at 14:29
  • @doctorlove OK I'll amend my answer. – john Oct 07 '13 at 14:47
  • Im still new to the template so I writing code and compiling and it worked. May I ask why I need const T& x ? – user2849898 Oct 07 '13 at 16:57
  • @user2849898 Both `T` and `const T&` are correct. But by using `const T&` you avoid making an extra copy of T when you push something onto your stack. T could be anything, it might be something that is very inefficient to copy. So that's why in this kind of code it's better to use `const T&` for a function parameter. – john Oct 07 '13 at 21:07