sc_ray
sc_ray

Reputation: 8043

Declaring STL Data Structures such as Vector in the .h

I am trying to declare a private Data Structure such as the Vector in my C++ header file which I want to eventually use within the method implementation of my .cpp.

An example would be my header "SomeClass.h" where I have:

class SomeClass
{
  private:
  Vector<T> myVector;
  public:
  void AddTtoMyVector(T add);
}

And in my .cpp which is "SomeClass.cpp", I have the following:

#include "SomeClass.h"

SomeClass::AddTtoMyVector(T add)
{
     myVector.Push_back(add);
}

Would the syntax here work? Or is there a different way of declaring and populating such structures?

Upvotes: 0

Views: 807

Answers (2)

Rakis
Rakis

Reputation: 7864

Following on to Artem's answer, it should be mentioned that although the standard practice for normal C++ classes is to place the declarations in the .h file and the implementations in a coresponding .cpp file, this typically applies only to non-template classes. If you're writing a template class, the entire implementation is usually placed in the same .h file that defines the template interface. There are a number of reasons for doing this and if you're planning on developing a template, I'd suggest investigating this issue a bit further right up front. It'll likely save you some time down the road.

Upvotes: 1

Artem Sokolov
Artem Sokolov

Reputation: 13691

Be sure to specify that you're using STL's vector, using either

std::vector<T> myVector;

or

using std::vector;

Also, if T is a generic type, you want to make the whole class templated:

#include <vector>

using std::vector;

template< typename T >
class SomeClass
{
  private:
  vector<T> myVector;
  public:
  void AddTtoMyVector(T add) {myVector.push_back( add );}
}

Upvotes: 2

Related Questions