Adding Header Files

Get practice working with declarations and definitions by creating a header file for one of our classes.
This lesson is part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

A screenshot showing a game environment
Ryan McCombe
Ryan McCombe
Posted

In this challenge, we will practice creating a header file for one of our classes.

Given we have the following class in a .cpp file, move the declaration into a .h file and use the cpp file for implementation. Remember to use a header guard!

// Character.cpp
class Character {
public:
  virtual void Attack(Character* Target){
    Target->TakeDamage(BaseDamage);
  };
  virtual void TakeDamage(int Amount){
    Health -= Amount;
  };
  bool isDead() { return Health <= 0; }
protected:
  int BaseDamage { 75 };
  int Health { 500 };
};
// Character.h
#pragma once

class Character {
public:
  virtual void Attack(Character* Target);
  virtual void TakeDamage(int Amount);
  bool isDead();
protected:
  int BaseDamage { 75 };
  int Health { 500 };
};
// Character.cpp
#include "Character.h"

void Character::Attack(Character* Target) {
  Target->TakeDamage(BaseDamage);
};

void Character::TakeDamage(int Amount) {
  Health -= Amount;
};

bool Character::isDead() { return Health <= 0; }

Was this lesson useful?

Ryan McCombe
Ryan McCombe
Posted
This lesson is part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

3D art showing a progammer setting up a development environment
This lesson is part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, unlimited access!

This course includes:

  • 66 Lessons
  • Over 200 Quiz Questions
  • Capstone Project
  • Regularly Updated
  • Help and FAQ
Next Lesson

C++ Namespaces and Using Declarations

Learn how we can use namespaces to keep related variables, functions and classes together.
3D art showing a fantasy character
Contact|Privacy Policy|Terms of Use
Copyright © 2023 - All Rights Reserved