Classes, seperate files.

Started by
5 comments, last by hogwash 19 years, 6 months ago
Well, I have two files, Tank.cpp and Tank.h . In Tank.h: class cTank; In Tank.cpp i have all of the constructor, destructor, etc for the cTank class. I thought that i could just include the Tank.h file in any .cpp file in which i need to use the cTank class. In my main loop, i do cTank a, then try and call one of cTanks functions. a.LoadModel("Data\Tank1.mdl"). This gives me an error saying that class cTank is undefined. Any ideas? I have run into this problem before and just side stepped it, but I am really going to need classes. Thanks.
Advertisement
You need to include the full class declaration, so the compiler knows the size of the class, and what functions it has. E.g. in Tank.h you need:
class cTank{public:   cTank();   ~cTank();   // Etcprivate:   int m_nXPos;   int m_nYPos;   // Etc};

Using class cTank; just lets the compiler know that there is a class called cTank. You'll only be able to pass around cTank*'s, since the compiler knows the size od a pointer, but not the size of the class. You also won't be able to call any member functions if you only have it declared like that, since the compiler doesn't know what functions exist.
Tank.h needs to have more than just
class cTank;

You need to add the complete prototype for it, e.g.:
class cTank{public:    cTank();    ~cTank();    LoadModel( ... );protected:    //bla bla bla};
SlimDX | Ventspace Blog | Twitter | Diverse teams make better games. I am currently hiring capable C++ engine developers in Baltimore, MD.
uhh.. only "class cTank;" in the header? try reading some elementary book or introduction to c++ that tells you how to define a class. nothing you read here in a short reply would be enough to fill the gap in your knowledge, to put it bluntly
Hmmm, well. To civguy, I know how to declare classes etc. The reason I was only including a small declaration for the class was because in previous instances when I did this and compiled it created link errors saying that the class has been declared twice. Thanks to everyone else though. I am going to mess around with it a little.

P.S. Don't you love it when people like to just attack? LoL.
I wasn't attacking, I gave my honest opinion and advice based on the type of your question. To fix multiple declarations, use inclusion guards. Again it's elementary knowledge, which, like I predicted in my previous message, no reply conveyed.
try putting the following around your code:

#ifndef TANK_H#define TANK_H#pragma once// class decl goes here#endif // TANK_H


This will fix the problem of it being included twice...

This topic is closed to new replies.

Advertisement