Sunday 26 July 2009

Initialising References in a class

Unassigned references cannot exist for a class. There is no C++ concept of an "unassigned reference" and the behavior of any program that has one is undefined. If a class contains a reference then it must be initialised through an initialiser list. You can't declare a reference variable in the class and then assign it later on. Non-reference variables and pointers can be left uninitialised but references must have a value upon entry. The only way to do this is through an initialiser.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example showing initializing of refrences in a class
#include<iostream>

using namespace
std;

class
A
{

public
:
A(string &name);
void
print()
{

cout<<"a = "<<a<<" and s = "<<s.c_str()<<endl;
}

void
set_a(int x) {a = x;}
private
:
A(); //Shouldnt really be called because we need to have a reference
int a;
string &s;
};


A::A(string &name): s(name)
{

//s = name; - error. Should be in initialiser
a = 0;
}


int
main()
{

string z = "zahid";
A a(z);
a.print();
z = "christian";
a.print();
a.set_a(30);
a.print();
return
0;
}

The output is as follows:

No comments:

Post a Comment