Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference variable in class definition

Tags:

c++

reference

I am learning C++, and I read that all references must be initialized upon declaration, and there can be no "uninitialized references". But what if the reference variable is a class member?

class test
{
    int &k;
};

int main()
{
    test *abc = new test;
}

This program compiles and runs normally (in g++, no warnings). However, abc->k is a reference, but what is it initialized to? Or, is it an "uninitialized reference" of some sort, or something else?

like image 295
ManRow Avatar asked Feb 19 '11 09:02

ManRow


2 Answers

The program is ill-formed because it constructs a class that fails to initialize a non-static member entity of reference type.

I believe that gcc should fail to compiler this, but I only received the warning "non-static reference ‘int& test::k’ in class without a constructor".

test is a non-POD-struct type as it contains a reference member. (9 [class] / 4)

new test default-initializes the dynamically allocated class. (5.3.4 [expr.new] / 15)

To default-initialize an object of type test means to call the implicitly declared and implicitly defined default constructor. (8.5 [dcl.init] / 5)

The implicitly defined default constructor is equivalent to a default constructor with an empty mem-initialized-list and an empty function body. (12.1 [class.ctor] / 7)

Further more:

The implicitly-defined default constructor performs the set of initializations of the class that would be performed by a user-written default constructor for that class with an empty mem-initializer-list (12.6.2) and an empty function body. If that user-written default constructor would be ill-formed, the program is ill-formed.

If an entity is not name in a mem-initializer-list and the member is not of class type [with further restrictions] then the entity is not initialized.

Otherwise, the entity is not initialized. If the entity is of const-qualified type, or reference type, [or ...] the program is ill-formed." (12.6.2 [class.base.init] / 4)

like image 144
CB Bailey Avatar answered Sep 21 '22 18:09

CB Bailey


Your code actually wont compile at all on Visual C++. In general it best to leave as little to chance as possible. You need to initialize refence members using an initialiser list in the constructor:

class test
{
public:
 test(int& x) : k(x)
 {
 }
 int& k;
};
like image 44
Jimmy Avatar answered Sep 20 '22 18:09

Jimmy