On this page
More_C++
IceCream
include/define
like python or Java import
Ilk.h:
class Ilk{
...
}
main.cpp
#include "Ilk.h" // like Ctrl+C and Ctrl+V
#define PIN_NUM 10 // like find and replace
...
int main(){
int newPinNum = PIN_NUM+2;
}
output:
class Ilk{
...
}
...
int main(){
int newPinNum = 10+2;
}
Header guards
#ifndef PICO_DRIVERS_H_
#define PICO_DRIVERS_H_
...
#endif // PICO_DRIVERS_H_
Pointers
Pass by ref
Arrays(and getting array length)
Namespaces
std::string myStr = "normal";
using namespace std;
string myStr = "with using keyword";
namespace std{
string myStr = "with brackets";
// ...
}
namespaces with class example:
namespace showUp{
class Jason{
...
}
}
...
int main(){
showUp::Jason();
}
Classes
#include <iostream>
#include <string>
using namespace std;
class Ilk
{
private:
int milk;
int private_func() {
return 69;
}
public:
Ilk(int milk) {
this->milk = milk;
}
~Ilk() {}
void drink(int galOfPilk) {
printf("drinking %dL of PILK\n", galOfPilk);
printf("%d\n", this->private_func());
}
int getMilk() {
return this->milk;
}
};
class Pilk : public Ilk
{
private:
string cola;
int numDrinks;
public:
Pilk(string cola, int numDrinks, int milk)
: cola(cola),
numDrinks(numDrinks),
Ilk(milk)
{
printf("pilk\n");
}
string getCola() {
return cola;
}
};
int main()
{
Ilk *i = new Ilk(420);
i->getMilk();
Pilk *p = new Pilk("coco cola", 420, 2);
p->drink(1337);
}
Header files
Unlike python or Java C/C++ splits its files
an .h file (header file) is as if you folded all the functions in Eclipse
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:
Ilk.h:
#include <iostream>
#include <string>
using namespace std;
class Ilk
{
private:
int milk;
int private_func();
public:
Ilk(int milk);
~Ilk();
void drink(int galOfPilk);
int getMilk();
};
Ilk.cpp:
#include <iostream>
#include <string>
#include "Ilk.h"
using namespace std;
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 <iostream>
#include <string>
#include "Ilk.h"
using namespace std;
int main() {
Ilk *i = new Ilk(420);
printf("%d\n",i->getMilk());
}