Page 1 of 1

C++ templates and operator overloading basics Rate Topic: -----

#1 BetaWar  Icon User is offline

  • #include "soul.h"
  • member icon

Reputation: 1201
  • View blog
  • Posts: 7,309
  • Joined: 07-September 06

Posted 09 October 2008 - 07:03 PM

Before we start
In this tutorial we will cover how to create basic templates and what is so great about using templates, as well as how to add operator overloads to classes you create.

To do this we will be creating a simple Account class that will allow for different types of data to be inputted.

Starting out
To start off lets learn how to create templates.

Create a new C++ file and type in the standard headers:
#include <iostream>
using namespace std;


To specify something is a template you need to create a class like so:
template <class T>
class Account{
  //stuff here
};


This creates the class called Account and tell it that it works as a template with the type called T.

Now that we have the simple class complete lets start filling things out. First off we will need a variable to use for the amount of money (or whatever) that is in the account. This is done like so:

template <class T>
class Account{
private:
  T amount;
};


This creates the variable amount of type T, simple enough. At this point in time you are probably starting to see how to specify data types through templates, so lets finish off the class (It needs to have a constructor, and a function that returns the amount):

template <class T>
class Account{
private:
  T amount;
public:
  Account(void){
    amount = 0;
  }
  Account(T initialValue){
    amount = initialValue;
  }
  T getAmount(void){
     return amount;
  }
};


You will notice the 2 contructors. This is known as constructor overloading, and basically acts like a check for different information being sent into the class constructor. Basically, if you call the constructor with no arguments it will set the amount to 0, otherwise, if a value with the datatype T is sent into the constructor it sets amount to the value sent in.

The main function
Now that we have the class basics in place we will create the main function to allow us to create multiple calls to our Account class with different datatypes.

Here is the main in full:
int main(void){
	typedef Account<int> intAccount;
	intAccount test(1000);
	cout << "Current balance: " << test.getAmount() << endl;
	return 0;
}


NOTICE - We are using typedef to say every Account of type int can be known as the datatype of intAccount. This makes things very easy because you could create multiple types of Account quickly.

If we wanted to also have an Account with the amount datatype of float we would do something like so:
int main(void){
	typedef Account<int> intAccount;
	typedef Account<float> floatAccount;
	intAccount test(1000);
	floatAccount test2(3.1415);
	cout << "Current int balance: " << test.getAmount() << endl; // outputs 1000
	cout << "Current float balance: " << test2.getAmount() << endl; // outputs 3.1415
	return 0;
}


You can also create multiple instances of the class with a single typedef like so:
int main(void){
	typedef Account<int> intAccount;
	intAccount test(1000);
	intAccount test2(314);
	cout << "Current int balance: " << test.getAmount() << endl; // outputs 1000
	cout << "Current int  balance2: " << test2.getAmount() << endl; // outputs 314
	return 0;
}


NOTICE - We have test2 as an integer now, instead of a float.

Operator Overloading
Operator overloading allows us to overload operators (as the name would suggest) for classes etc. Here we will take a look at how to set the amount held in our Account class by overloading the = operator for our class.

template <class T>
class Account{
private:
  T amount;
public:
  Account(void){
    amount = 0;
  }
  Account(T initialValue){
    amount = initialValue;
  }
  T getAmount(void){
     return amount;
  }
  void operator=(T newVal){
    amount = newVal;
  }
};


Yes, those three lines of code overloaded the = operator for Account so, now we can make quick updates to the amount help in our instance of the class like so:
int main(void){
	typedef Account<int> intAccount;
	intAccount test(1000);
	intAccount test2(314);
	test2 = 900;
	cout << "Current int balance: " << test.getAmount() << endl; // outputs 1000
	cout << "Current int  balance2: " << test2.getAmount() << endl; // outputs 900
	return 0;
}


Wrapping up
Here is a full code I have created that allows for more operator overloads, and an example of it working:

#include <iostream>
using namespace std;

template <class T>
class Account{
private:
	T amount;
public:
	Account(T initAmt){
		amount = initAmt;
	}
	Account(void){
		amount = 0;
	}
	~Account(void){
	}
	T getAmt(void){
		return amount;
	}
	void operator=(T newVal){
		amount = newVal;
	}
	void operator+=(T addVal){
		amount += addVal;
	}
	void operator-=(T subVal){
		amount -= subVal;
	}
	void operator*=(T multVal){
		amount *= multVal;
	}
	void operator/=(T divVal){
		amount /= divVal;
	}

};

int main(void){
	typedef Account<int> intAccount;
	intAccount test(1000);
	test = 12354;
	test += 10;
	cout << "Current balance: " << test.getAmt() << endl;
	return 0;
}


The end
Hope you all got something out of this :)

Is This A Good Question/Topic? 1
  • +

Replies To: C++ templates and operator overloading basics

#2 gabehabe  Icon User is offline

  • GabehabeSwamp
  • member icon




Reputation: 1385
  • View blog
  • Posts: 10,962
  • Joined: 06-February 08

Posted 10 October 2008 - 04:16 AM

Nice write up :^:
Was This Post Helpful? 0
  • +
  • -

#3 msjaiswal  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 28-May 09

Posted 28 May 2009 - 06:41 AM

Hello BetaWar!

Thanks for a very well organized tutorial.

It can be a little more useful if you can show us how to declare the functions out of the class.
For example:


void Classname :: FunctionName (Type a)
{

// code
}



Kindly add an example where all the functions (including operator Overloading functions ) are only declared in the class and are actually defined in the format as I have shown above.



Thanks in advance.
Mayank
:)
Was This Post Helpful? 0
  • +
  • -

#4 Ratstail91  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 11-January 10

Posted 18 January 2010 - 11:47 PM

View Postmsjaiswal, on 28 May, 2009 - 05:41 AM, said:

Hello BetaWar!

Thanks for a very well organized tutorial.

It can be a little more useful if you can show us how to declare the functions out of the class.
For example:


void Classname :: FunctionName (Type a)
{

// code
}



Kindly add an example where all the functions (including operator Overloading functions ) are only declared in the class and are actually defined in the format as I have shown above.



Thanks in advance.
Mayank
:)


that's unnecessary. usually, one-line functions (or two line functions, or course that's pushing it) should be declared inside the class for convenience. if you want one declared like that, do it yourself.
Was This Post Helpful? 0
  • +
  • -

#5 darek9576  Icon User is offline

  • D.I.C Lover

Reputation: 198
  • View blog
  • Posts: 1,693
  • Joined: 13-March 10

Posted 01 August 2014 - 08:30 AM

Why would the constructor that does the following compile:

amount = 0;


What if amount is of type Apples. Can someone explain or is it just an error in the tutorial.
Was This Post Helpful? 0
  • +
  • -

#6 Anarion  Icon User is offline

  • The Persian Coder
  • member icon

Reputation: 311
  • View blog
  • Posts: 1,515
  • Joined: 16-May 09

Posted 20 November 2014 - 09:56 AM

View Postdarek9576, on 01 August 2014 - 07:00 PM, said:

Why would the constructor that does the following compile:
amount = 0;
What if amount is of type Apples. Can someone explain or is it just an error in the tutorial.

Well, try this:
class mytype {};

int main(){
	Account<mytype> m;
	return 0;
}

If you try to compile the above code (including the class definition for Account of course!), you are going to get compile errors because there is no operator= defined for mytype, which is because operator= is used in the constructor as you noted. Not only that, try any of the implemented operations after it and there will be more errors. So, this class only works with types which have the needed operators defined for them.

Edit: Not intended to revive an old conversation, it was rather as a side-note because it's a tutorial section :)

This post has been edited by Anarion: 20 November 2014 - 09:59 AM

Was This Post Helpful? 0
  • +
  • -

#7 BetaWar  Icon User is offline

  • #include "soul.h"
  • member icon

Reputation: 1201
  • View blog
  • Posts: 7,309
  • Joined: 07-September 06

Posted 20 November 2014 - 01:17 PM

I think the primary issue there was an unspoken assumption that the account would store numeric types (ints, doubles, and the like). Though, as @Anarion stated, it will work with anything that has the appropriate operators.

Though, this tutorial is also 6 years old, so I can't speak completely for my state of mind when I wrote it :)
Was This Post Helpful? 0
  • +
  • -

#8 Anarion  Icon User is offline

  • The Persian Coder
  • member icon

Reputation: 311
  • View blog
  • Posts: 1,515
  • Joined: 16-May 09

Posted 20 November 2014 - 02:46 PM

View PostBetaWar, on 20 November 2014 - 11:47 PM, said:

I think the primary issue there was an unspoken assumption that the account would store numeric types (ints, doubles, and the like). Though, as @Anarion stated, it will work with anything that has the appropriate operators.

Though, this tutorial is also 6 years old, so I can't speak completely for my state of mind when I wrote it :)/>

At first I wasn't seeing the date, and right after I posted it, I was like "wow way to go! I just revived an ancient post!" It felt so bad and noob! :whistling:
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1