chocobo_ff
chocobo_ff

Reputation: 45

Initialise reference variable as a class member

I am trying to convert a function from a camera SDK I am using to a class, so I can call the different parts of the function separately (initialisation, capture image, clean up). A problem I am having is that some variables in the function are defined as:

type& var = type::init();

This doesn't work when I do:

class myClass
{
private:
type& var;
};

I've tried to change:

type& var;

To:

type* var;

And that worked fine when I had everything in a single function, but when I try to break it up into separate functions in a class, the code compiles but doesn't run. Is there something fundamentally wrong with my code?

EDIT: The code is from Basler's SDK, the original code is:

Pylon::CTlFactory& TlFactory = Pylon::CTlFactory::GetInstance();

In the header file:

Pylon::CTlFactory *TlFactory;

And the cpp file:

TlFactory = &Pylon::CTlFactory::GetInstance();

As mentioned, when all the code is in a single function, it compiles and runs fine, it's only when I break it up into class functions that I have problems...

Upvotes: 0

Views: 1460

Answers (3)

Ayjay
Ayjay

Reputation: 3433

class myClass
{
public:
    myClass() : var(Pylon::CTlFactory::GetInstance())
    {
        // rest of init logic
    }
private:
    Pylon::CTlFactory& var;
};

Upvotes: 0

CapelliC
CapelliC

Reputation: 60014

In addition to the answer of K-ballo, note this (useful, IMO) feature of C++ scoping rules: you can expose the very same name as formal parameter in the constructor. This allows handy code cut & paste, avoiding the need to dream of 'use once' names.

class myClass
{
public:
    myClass( type& var )
      : var( var )
    {}

private:
    type& var;
};

Upvotes: 0

K-ballo
K-ballo

Reputation: 81349

References are not assignable. When you have a reference as a class member object, you need to initialize it in the constructor. For that, you use the constructor initialization list:

class myClass
{
public:
    myClass( type& some_var )
      : var( some_var )
    {}

private:
    type& var;
};

Upvotes: 7

Related Questions