An Overflowed Stack
An Overflowed Stack

Reputation: 344

Why does my code throw "does not name a type error"?

driver.cc

#include <iostream>

#include "dynStack.h"

using namespace std;

// class definition
int main()
{
  dynstack<double> it;
  cout << "hello";
  return 0;
}

dynStack.h

template <class T>
class dynstack {
public:
  dynstack();
  void push(T data);
private:


};

#include "dynStack.cc"

dynStack.cc

template <class T>
dynstack<T>::dynstack() { // <-- Here

}

template <class T> //  // <-- And here
void dynstack<T>::push(T data)
{
}

I'm new to C++. The bolded lines are reported errors. The first one says "error: 'dynStack' does not name a type" The second one says "exrror: expected initializer before '<' token". I have spent hours on this and can't find the errors. Can anyone help? Thank you.

I was given a sample solution similar to this. Here is the sample:

main.cc

#include <iostream>
// #include the header file - as always
#include "temp.h"

using namespace std;

int main()
{
  Thing<int> it(1);

  Thing<double> dt(3.14);

  cout << endl;
  cout << "it = " << it.getData() << endl;
  cout << endl;
  cout << "dt = " << dt.getData() << endl;
  cout << endl;

  return 0;
}

temp.h

template <class T>
class Thing
{
  private:
    T data;
    void setData(T data);

  public:
    Thing(T data);
    T getData() const;
};

// MUST #include the implementation file here
#include "temp.cc"

temp.cc

// DO NOT #include the header file

template <class T>
Thing<T>::Thing(T data)
{
  this->setData(data);
}

template <class T>
void Thing<T>::setData(T data)
{
  this->data = data;
}

template <class T>
T Thing<T>::getData() const
{
  return this->data;
}

Upvotes: 0

Views: 887

Answers (2)

David Hammen
David Hammen

Reputation: 33136

It appears that you are trying to compile both driver.cc and dynStack.cc. The only file you compile with this setup is driver.cc.

Upvotes: 3

Arun
Arun

Reputation: 20403

Try this: Move contents of dynstack.cc entirely to dynstack.h and get rid of dynstack.cc

EDIT after reading comment responses:

If you want to keep dynstack.cc, its fine, just make sure you do not attempt to compile dynstack.cc I would name it a some other extension other than .cc which is conventionally for C++ implementation. Avoid .cc, .cpp, .cxx etc; use a uncommon extension such as .hc :-)

Upvotes: 1

Related Questions