Difference between revisions of "SimpleObject class"
(→Source File) |
(→Source File) |
||
Line 38: | Line 38: | ||
using namespace std; | using namespace std; | ||
+ | |||
SimpleObj::SimpleObj() // constructor | SimpleObj::SimpleObj() // constructor | ||
{ | { |
Revision as of 09:58, 13 June 2019
In C++ a class should have 2 separate files, one with the ".h" extension which is a header file, and one with the ".cpp" extension which contains the code for the class.
Header File
If you are using Visual Studio, find the 'Solution Explorer' and right click on 'Header Files', then select 'Add' and then 'New Item'. From this interface select 'Header File' and give it the name 'SimpleObj.h'.
Now we have created the file, enter the following code:
#pragma once
#include <string> // we're going to use strings so need the header
using namespace std;
class SimpleObj
{
public:
SimpleObj(); //standard constructor
~SimpleObj(); //standard destructor
//list the functions we want to have (called methods in C++)
void Update();
void Draw();
// list the variables we want our instances to have (called members in C++)
int m_Counter;
string m_MyName ;
};
This should be saved as SimpleObj.h , the class includes a constructor and destructor and methods for Update and draw. The class also lists 2 variables that each instance will inherit. The class uses a string, so the include line is essential to load the string library. the #pragma once line is just to do with compiling, it means it will compile it only once no matter how many times it is used.
Source File
If you are using Visual Studio, find the 'Solution Explorer' and right click on 'Source Files', then select 'Add' and then 'New Item'. From this interface select 'Source File' and give it the name 'SimpleObj.cpp'.
Now we have created the file, enter the following code:
#include <iostream> // we need this to output to console this file contains cout
#include "SimpleObj.h" // we need to load the class header
using namespace std;
SimpleObj::SimpleObj() // constructor
{
m_Counter = 0; // make sure the counter starts at 0
}
SimpleObj::~SimpleObj() {} // no code yet in the destructor
void SimpleObj::Update()
{
// output our name and keep track of our internal counter
cout << "Hello my name is " + m_MyName + " and I've looped this many times " << m_Counter << endl;
m_Counter = m_Counter + 1;
}
void SimpleObj::Draw() {} // no code yet in the draw
Our class will set the counter to zero when an instance of the class is created. When Update is called a message is produced including the number of times the message has been written. It will then increment the counter. Remember to save this as SimpleObj.cpp.
Usage
You can use this as a simple template for creating a class, in a game you will have many classes but all will be defined in a similar way. You will obviously decide which methods are required, and which variables are needed.