Difference between revisions of "SimpleObject class"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
Line 4: Line 4:
 
#pragma once
 
#pragma once
 
#include <string> // we're going to use strings so need the header
 
#include <string> // we're going to use strings so need the header
 +
 +
using namespace std;
 +
 
class SimpleObj
 
class SimpleObj
 
{
 
{
Line 14: Line 17:
 
// list the variables we want our instances to have (called members in C++)
 
// list the variables we want our instances to have (called members in C++)
 
int m_Counter;
 
int m_Counter;
std::string m_MyName ;
+
string m_MyName ;
 
};
 
};
 
</syntaxhighlight>
 
</syntaxhighlight>

Revision as of 09:52, 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. To make a simple class we can therefore create the following header file:

#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.

Now for some code for the class, we need to create the cpp file:

#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;
//	cout << this->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.