c++ - Class declarations in header files -
ive been using c++ months ive come across error when use header , source code files. create source code file contains class gun(example not actual program):
class gun { private: int stuff; public: void dostuff(); }; void gun::dostuff() { cout << stuff << endl; }
and created header file , declared class this:
class gun;
then in main source file this:
int main() { gun *mygun = new gun; mygun->dostuff(); return 0; }
however when try execute error: invalid use of incomplete type 'class gun' , think problem how declared in header, did wrong? how meant it? thanks.
thanks helped! understand now, thought forward declaration went header file, answers!
you seem going seperating implementation , header file wrong way. forward declarations should not go in header file. entire declaration should! how code should structured
gun.hpp
#pragma once class gun { private: int stuff; public: void dostuff(); };
gun.cpp
#include "gun.hpp" #include <iostream> using std::cout; using std::endl; void gun::dostuff() { cout << stuff << endl; }
main.cpp
int main() { gun *mygun = new gun; mygun->dostuff(); delete mygun; // <-- remember this! return 0; }
the separation of header , implementation crucial in c++ , other languages! should declare class in header along full interface (as above) , include implementation details in .cpp file (as above :)
Comments
Post a Comment