SimpleObject class

From TRCCompSci - AQA Computer Science
Revision as of 15:28, 30 March 2018 by Admin (talk | contribs) (Created page with "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 ma...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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
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;
	std::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