1. Home
  2. Computing & Technology
  3. C / C++ / C#

C++ Tutorial - Learn to use References

By , About.com Guide

6 of 7

References and Initializer lists

// 8_4.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

class gamedata; // make available to game and map classes
class map {

int mapsize;
public :
map( int newmapsize) { mapsize=newmapsize;};

};


class army {

int armysize;
public :
army( int newarmysize) { armysize = newarmysize;};

};

class game {

map & m;
army & a;
public :
gamedata( map & amap, army & anarmy) ;
};

gamedata::gamedata( map & amap, army & anarmy) : m(amap), a(anarmy) {}

int main(int argc, char* argv[])
{
map amap(1) ;
army anarmy(10) ;
gamedata g(amap,anarmy) ;
return 0;
}
The army class is decoupled from the map class and vice versa. We need to tie armies to maps so, we need access to the (externally defined) map and army objects in this class. This can be done in the gamedata class and to make this possible, include references to both map and army objects.

In a constructor, you cannot assign a value to a reference except when it is created, ie initialized. The initializer lists provides a way to do this before the body of the constructor is called. In example 8_4, both amap and anarmy exist elsewhere before the gamedata constructor is called.

On the next Page : More about decoupling classes

Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. References and Initializer lists

©2009 About.com, a part of The New York Times Company.

All rights reserved.