Classes in C++
The nice thing about C++ being compatible with C is that you don’t have to use classes if you don’t want to.
Classes
A basic example of a class looks like so:
#include <string>
class Animal {
int weight;
std::string name;
};
Remember to include the semicolon ;
at the end of classes.
Access Modifiers
We can use the following access modifiers:
public
- You can access it from anywhere.private
- You can only access them from within the class or from friends.protected
- You can only access them from this class, sub-classes or from friends.
The default is private
.
The syntax is like so:
#include <string>
class Animal {
public:
int weight;
std::string name;
};
Getters & Setters
#include <string>
#include <iostream>
using namespace std;
class Animal {
private:
int weight;
string name;
public:
void setWeight(int value) {
weight = value;
}
int getWeight(void) {
return weight;
}
};
int main() {
Animal example; // Creates the object
example.setWeight(55);
cout << example.getWeight();
}
Using Headers
We should put the following in header files:
- Class Definitions
- Constants
This will split our code like so:
Animal.h:
#include <string>
namespace ani {
class Animal {
private:
int weight;
std::string name;
public:
void setWeight(int value);
int getWeight(void);
};
}
You should not using namespace ...
in header files.
Animal.cpp
#include "Animal.h"
int ani::Animal::getWeight() {
return weight
}
void ani::Animal::setWeight(int value) {
weight = value;
}
main.cpp
#include <iostream>
#include "Animal.h"
using namespace ani;
using namespace std;
int main() {
Animal example;
cout << example.getWeight();
}
We can declare multiple namespaces (provided they don’t clash).
Constructors & Destructors
Constructors are used to allocate memory and initialise objects, whereas destructors free the memory. We can extend our header files to allow for this functionality:
Animal.h:
#include <string>
namespace ani {
class Animal {
private:
int weight;
std::string name;
public:
void setWeight(int value);
int getWeight(void);
Animal(int value);
~Animal();
};
}
Animal.cpp
#include "Animal.h"
int ani::Animal::getWeight() {
return weight
}
void ani::Animal::setWeight(int value) {
weight = value;
}
ani::Animal::Animal(int value) {
weight = value;
}
ani::Animal::~Animal() {} // You can skip this as this does the same as the default
Member Initialisation
To save us manually initialising variables in our constructors, we can use the following syntax:
ani::Animal::Animal(int value) : weight(value) {}