+ 2

What is this difference in C++?

I've been wondering, is there a difference between the following code, and if so, what is the difference? class Example { public: void greet() { cout << "Hello." << endl; } }; AND class Example { public: void greet(); }; void Example::greet() { cout << "Hello." << endl; }

19th May 2018, 1:47 AM
Physh
Physh - avatar
5 Answers
+ 1
So if I had a like "base.h" that included the Example class above: class Example { public: void greet(); }; And another file called, say, base.cpp that was: #include "base.h" using namespace std; void Example::greet() { cout << "Hello" << endl; } That is how it would work?
19th May 2018, 2:01 AM
Physh
Physh - avatar
0
These two effectively do the same thing, but the second one defines the function outside of the class. You may do this if you want a header file (.h) with just the class members and function prototypes separate from the source file (.cpp) with the function definitions. Notice how you need to use the scope resolution (::) operator in the second example in order to say that you are defining the function that is in the class Example.
19th May 2018, 1:55 AM
Caroline
0
@怌ļ¼Øļ¼”ļ¼°ļ¼°ļ¼¹ ļ¼“ļ¼Æ ļ¼Øļ¼„ļ¼¬ļ¼°ć€ So how exactly do .h files work? Is that where you use #include? As in, in the .cpp files do you use #include the .h files
19th May 2018, 1:56 AM
Physh
Physh - avatar
0
Why is that an error? Sorry for so many questions just learning
19th May 2018, 2:02 AM
Physh
Physh - avatar
0
Oh yeah I was just assuming that iostream was included, but okay. Like the class suggests, just an example :P
19th May 2018, 2:07 AM
Physh
Physh - avatar