CPP Class

In CPP a class will have 2 main components:

  1. Header file (like interface file)
  2. Cpp file (main logic)

Consider the following example

dog.hpp

#include <iostream>

class Dog {
    std::string name;
    int weight;

public:
    // constructor
    Dog();
    Dog(std::string name);
    Dog(std::string name, const int weight);

    void setName(const std::string dogName);

    void setWeight(int dogWeight);

    // 'virtual' indicate that this function won't change the class (Read only)
    // So that we can still calll this function if object is const
    virtual void print() const;

    // We can do implementation here for default implementation
    void bark() const {
        std::cout << name << ": bark!" << std::endl;
    }

    // Destructor
    virtual ~Dog();
};

dog.cpp

#include "dog.hpp"

Dog::Dog() {
    std::cout << "Intialised Dog" << std::endl;
};

Dog::Dog(const std::string name) {
    Dog::name = name; // or this->name = name;
    std::cout << "Intialised Dog with name: " << name << std::endl;
};

Dog::Dog(const std::string name, const int weight) {
    std::cout << "Intialised Dog with name: " << name
    << " and weight: " << weight;
};

void Dog::setName(const std::string dogName) {
    Dog::name = dogName;
}

void Dog::print() const {
    std::cout << "Print the dog" << std::endl;
}


Dog::~Dog() {
    std::cout << "Destroyed dog: " << name << std::endl;
};

main.cpp

#include "dog.hpp"

int main() {
    Dog myDog ("Adam");
    myDog.bark();

    Dog friendDog ("Betan");
    friendDog.bark();

    Dog somedog;
    somedog.bark();


    Dog others[] = {
        Dog("Other1"),
        Dog("Other2"),
        Dog("Other3"),
    };

    for (int i = 0; i < 3; i++) {
        others[i].bark();
    }

    return 0;
}

Make

all: clean compile build

clean:
	@rm -rf build/*

compile: clean
	@g++ -c dog.cpp -o build/dog.o 
	@g++ -c main.cpp -o build/main.o

build: compile
	@g++ build/dog.o build/main.o -o build/main