Reputation: 4298
When I created a new project Visual Studio 2012 created three files that I'm interested in: Stdafx.h, MyProj.h and MyProj.cpp. In MyProj.h Visual Studio created a "ref class" but I was never able to get the project to compile with the ref class there. I moved the ref class to the MyProj.cpp file, and the project now compiles fine. Why would a "ref class" be in the .h file instead of the .cpp file?
Upvotes: 0
Views: 416
Reputation: 942267
You have to understand the way C++ code is compiled and linked. It is very different from the languages you are used to, Java and C#. C++ doesn't have a standard way to break up your code into modules. Every source code file is compiled separately and produces an object file. Then they get glued together by the linker to make a program.
So if you have two source code files that use your class then they need to know what that class looks like. You do so by putting the declaration of the class in a .h file. Boilerplate is then to put the implementation of the class members in a .cpp file.
Which is what the project template gave you, a ref class in the .h file, ready for you to add member declarations to. And an empty .cpp file, ready for you to put the member definitions into.
This actually isn't that necessary anymore in C++/CLI because it is a language that actually does have modules. You know them from C#, called assemblies. And if other code, written in a different language, needs to know what the class looks like then you add a reference to the assembly. The compiler reads the class declaration from the metadata in the assembly, no .h file needed. But you'll still need a .h file if you have two .cpp files that get linked into a single assembly.
In general you'll want to pick up a introductory book about C++ programming. You'll need to know some of the basics to make effective use of C++/CLI. Such a book will certainly talk about header files and show how you split the declaration and implementation.
Upvotes: 1
Reputation: 283813
It's the same reason type definitions go into header files in normal C++: To help you keep definitions in agreement between all source files.
Header files are basically automated copy+paste, that guarantees you don't forget to change one of the copies.
(If different files ever start using different definitions for the same type, you violate the One Definition Rule, and the language gives no limitations on the bad things that can start to happen.)
Upvotes: 0