Thursday 10 November 2016

Overloaded with overloading

In creating a custom Vector3 class and the necessary overloaded methods I assumed it would be relatively easy task. Its only as you begin to look at some of the overloading possibilities that one begins to realise that programmers can easily get bogged down and overloaded pretty quickly ;-). Its with this in mind that the following suggested code snippets were put together

The Vector3 header contains a friend operator+ overload (Line 5) and a class operator- overload (Line 14)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
namespace custom
{
 class Vector3
 {
  friend Vector3 operator+(Vector3, const Vector3&);
 public:
  Vector3();
  Vector3(double, double, double);
  Vector3(const Vector3&);
  ~Vector3();
  const double getX();
  const double getY();
  const double getZ();
  const Vector3 operator-(const Vector3&) const;
 private:
  double m_x, m_y, m_z;
 };
}


The Vector3.cpp file below contains the definitions for the two overloads


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <Vector3.h>

using namespace custom;

Vector3::Vector3() : m_x(0.0f), m_y(0.0f), m_z(0.0f){ }

Vector3::Vector3(double x, double y, double z) : m_x(x), m_y(y), m_z(z) { }

Vector3::Vector3(const Vector3& o) : m_x(o.m_x), m_y(o.m_y), m_z(o.m_z) { }

Vector3::~Vector3() { }

const double Vector3::getX() { return m_x; }

const double Vector3::getY() { return m_y; }

const double Vector3::getZ() { return m_z; }

const Vector3 Vector3::operator-(const Vector3& v) const
{
 return Vector3(m_x - v.m_x, m_y - v.m_y, m_z - v.m_z);
}

custom::Vector3 custom::operator+(custom::Vector3 v1, const custom::Vector3& v2)
{
 return Vector3(v1.m_x + v2.m_x, v1.m_y + v2.m_y, v1.m_z + v2.m_z);
}


Note the use of custom namespace which avoids any clashes with other Vector3 classes already defined.


Next a SFML an project was created and a draw() method defined which was added to the GameLoop

To preserve memory (this memory now needs to be managed) a static variable v was initialized and updated in line 5. The + and - operations and now interchangeable. This lead me to read these  CppReference articles on operator overloading and use of friend functions.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
static custom::Vector3 v(0.0, 2.0, -5.0);

void Game::draw()
{
 v = v - custom::Vector3(0.0f, 0.0001f, 0.0f);
 cout << "Draw up" << endl;
 cout << "[x]" << v.getX() << " [y]" << v.getY() << " [z]" << v.getZ() << endl;
 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  
 glBegin(GL_TRIANGLES);{ 
   glVertex3f(GLfloat(v.getX()), GLfloat(v.getY()), GLfloat(v.getZ()));
   glVertex3f(-2.0, -2.0, -5.0);
   glVertex3f(2.0, -2.0, -5.0);
 } 
 glEnd();

 window.display();
}




No comments:

Post a Comment