Menu
C++ Tutorials

C++

Advanced Structures



Tutorials > C++ > Advanced Structures

View Full Source

Introduction

In the last tutorial, we saw how variables can be placed within structures. In this tutorial, we will see how functions and constructors(initializers) can be placed within structures.

What are Constructors?

A constructor is another function that is run when a variable is first created. The function has no return value and its name is the same as that of the structure. Extra parameters are optional. More than one constructor can be used as long as their parameters differ.

Contents of main.cpp :


#include <iostream>
#include <stdlib.h>

using namespace std;

Below we add a constructor to our Player structure. The constructor takes one parameter which is the name of the player. The player's health is initialized to 100.

struct Player
{
	char *name;
	int health;

	Player(char *n) 
	{ 
		name = n; 
		health = 100;
	}
};

There are 2 modifications to the structure below. The one modification is in the constructor. An initializer list can be placed after the constructor's signature to initialize variable. This is done by placing a : after the signature. Each variable needing initialization can be placed after the : with the initialized value placed in brackets. Each variable is separated by a comma. The constructor below could have been rewritten as :

    Enemy(char *n) : name(n), health(100) {}

A function has also been added to the structure. The function is created as per normal except that the function can access any variable declared within the structure. In this case, our function decreases the enemie's health by a specified amount.

struct Enemy
{
	char *name;
	int health;

	Enemy(char *n) : name(n)
	{
		health = 100;
	}

	void decreaseHealth(int amount)
	{
		health -= amount;
	}
};

int main()
{

As we did not have a default constructor(constructor with no parameters), we have to specify a parameter when creating the structure variable.

	Player player1("Bob");
	cout << player1.name << endl;

Functions can be accessed in the same way as variables by using the dot(.) operator. After calling the decreaseHealth function with a parameter of 20, you will notice that the health variable now represents the value of 80.

	Enemy enemy("Dr. Evil");
	cout << enemy.name << endl;
	enemy.decreaseHealth(20);
	cout << enemy.health << endl;

	system("pause");

	return 0;
}

Hopefully you should now be able to utilize structs in such a way to replicate real world scenarios more easily. Structs provide a great way to encapsulate data for a specific entity.

Please let me know of any comments you may have : Contact Me

Source Files : Visual Studio Dev-C++ Unix / Linux

< Tutorial 27 - Structures Tutorial 29 - Typecasting >

Back to Top


All Rights Reserved, © Zeus Communication, Multimedia & Development 2004-2005

Read the Disclaimer

Links