On this page
Header files
Unlike python or Java C/C++ splits its files
Why do we do this??
In C++ we can’t use a function until we have defined it
EX:
int main(){
printf("%d\n" funnyNumber()); // this wont work
}
int funnyNumber(){
return 69;
}
To fix this we use forward declaration
int funnyNumber(); // forward declaration
int main(){
printf("%d\n" funnyNumber()); // this wont work
}
int funnyNumber(){
return 69;
}
we say “Hey C++ here I promise I will eventually define this function funnyNumber
but don’t freak out when you see it”
Here is a link that goes more in depth: https://www.learncpp.com/cpp-tutorial/classes-and-header-files/
.h
file (header file) is like we deleted the body of the function
ILoveBen.h
int ILoveBen();
ILoveBen.cpp
#include "ILoveBen.h"
int ILoveBen(){
return 10;
}
main.cpp
#include "ILoveBen.h"
int main(){
printf("%d\\n",ILoveBen());
}
Classes in header files example:
TODO explain y classes have a :: in .cpp file
Ilk.h:
class Ilk
{
private:
int milk;
int private_func();
public:
Ilk(int milk);
~Ilk();
void drink(int galOfPilk);
int getMilk();
};
Ilk.cpp:
#include "Ilk.h"
int Ilk::private_func() {
return 69;
}
Ilk::Ilk(int milk) {
this->milk = milk;
}
Ilk::~Ilk() {}
void Ilk::drink(int galOfPilk) {
printf("drinking %dL of PILK\n", galOfPilk);
printf("%d\n", this->private_func());
}
int Ilk::getMilk() {
return this->milk;
}
main.cpp:
#include "Ilk.h"
int main() {
Ilk *i = new Ilk(420);
printf("%d\n",i->getMilk());
}