0

I am learning about C++ classes and I realized that if I tried to move my class declaration and definition of class Date from main.cpp to another c++ file, say test.cpp and compiled the two files I got an error saying Date was not declared. Why is that?

smilingbuddha
  • 12,744
  • 28
  • 97
  • 169
  • 4
    Please include more information or post code. For compilation errors like this it's more important that the class is defined (usually from another .h file and through an #include directive.) – Chris A. Sep 26 '11 at 21:22
  • @ChrisA.: Do you mean *declared*? – bitmask Sep 26 '11 at 21:37
  • You might want to read [this answer](http://stackoverflow.com/questions/6923961/source-file-and-header-in-c/6924146#6924146) – sbi Sep 26 '11 at 22:01
  • 1
    @bitmask: More likely Chris is talking about a class _definition_. A class _declaration_ is used rarely. See [this answer](http://stackoverflow.com/questions/1410563/what-is-the-difference-between-a-definition-and-a-declaration/1410632#1410632) for the difference. – sbi Sep 26 '11 at 22:03
  • @sbi: `me += knowledge` ... I've been using the wrong words for ages. Thanks! – bitmask Sep 26 '11 at 22:16
  • Yes, "declared" would have been sufficient. "Class definition" also works. – Chris A. Sep 26 '11 at 23:43
  • @ChrisA.: There is a big difference between a class _declaration_ and a class _definition_. (For example, you cannot access any members of a class that's only been _declared_.) Please see the link I provided. – sbi Sep 27 '11 at 07:16
  • @sbi, I understand that difference and was saying you're correct. I misspoke in my original statement and was suggesting two possible corrections that make the statement correct. – Chris A. Sep 27 '11 at 23:47
  • @ChrisA: Ah, sorry for misunderstanding you. – sbi Sep 28 '11 at 04:07

2 Answers2

2

This is why you have header files. You need a header file test.h that contains only the class definition (that is mostly function declarations) and test.cpp that contains the actual function definitions (the code).

In main.cpp you'll have to #include "test.h".

Blagovest Buyukliev
  • 39,704
  • 12
  • 88
  • 124
  • 1
    You probably need the class *definition* (but not any *function definitions*) in the header file, otherwise you'll have to deal with it as an incomplete type. – R. Martinho Fernandes Sep 26 '11 at 21:27
  • Note that the rules are completely different for template types, and that static variables should be instantiated in the .cpp file. – Mooing Duck Sep 26 '11 at 21:43
0

Well, you would have to declare your class in test.h and include it in main.cpp so that the compiler knows where to look for it and you can then define your class in test.cpp

Mansuro
  • 4,194
  • 4
  • 31
  • 72