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

C++ Tutorial - Copy Constructors

By , About.com Guide

4 of 10

Initializing References

An unassigned reference (for more on references, see the C++ tutorial on references) cannot exist. There is no C++ concept of an "unassigned reference" and the behavior of any program with one is not defined. If a class contains a reference then it must either be created and assigned in the constructor or through an initializer 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 uninitialized but references must have a value upon entry. The only way to do this is through an initializer.

#include <iostream>

using namespace std;

struct refed {
    int rd;
};

class a {
  public:

    refed & r;
    int x;
    int ℞

    a(refed & extr) : r(extr), rx(x) { }
};

void main() {
    refed ref;
    a A(ref) ;
    A.x=9;
    A.r.rd=47;
    cout << "Value of rx=" << A.rx <<endl;
    cout << "Value of A.r.r=" << A.r.rd <<endl;
}
In this example class a has two reference variables. One is to class refed (it's a struct but apart from all members being public, is the same as a class) and one is to an int variable.

Default Constructors for Ints etc

Though they are not objects, the non class types such as int, float, char and bool do have a default constructor! It doesn't allocate any memory but does initialize the variable.
int a(8) ;
bool b(true) ;

and

class c {
  int a;
};

c * v = new c;
int * x = new int (6) ;

On the next page Creating and Using Copy Constructors

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. Initializing References

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

All rights reserved.