By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,478 Members | 1,703 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,478 IT Pros & Developers. It's quick & easy.

Initializing class member variable with reference

P: n/a

Hi all,

I need to pass reference to a class via constructor,
to initialize its member variable. This is the code simplified :
class Logger{

public :
Logger(string filename);
};

class Destination{

public :
Destination(Logger &log)

private:
Logger mylogger;
};

int main(int argc, char* argv[]){

Logger logger("logger.config");
Destination dest(logger);

}
In this case, Logger class doesn't have no-args constructor.
How can I pass (by reference ) Logger instance I create on
main function? By now, I do it by defining member variable
mylogger as reference, such this :

private :
Logger& mylogger

and I initialize it using initialization list in constructor
Destination::Destination(Logger& log):mylogger(log){}

Is the way I did it correct ? Or any side effect that I have to
take care ?
Thanks in advance.

Nov 22 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
chris wrote:
I need to pass reference to a class via constructor,
to initialize its member variable. This is the code simplified :
class Logger{

public :
Logger(string filename);
Better:

Logger(string const& filename);
};

class Destination{

public :
Destination(Logger &log)

private:
Logger mylogger;
Shouldn't this be

Logger& mylogger;

???
};

int main(int argc, char* argv[]){

Logger logger("logger.config");
Destination dest(logger);

}
In this case, Logger class doesn't have no-args constructor.
How can I pass (by reference ) Logger instance I create on
main function? By now, I do it by defining member variable
mylogger as reference, such this :

private :
Logger& mylogger
That's better.

and I initialize it using initialization list in constructor
Destination::Destination(Logger& log):mylogger(log){}

Is the way I did it correct ? Or any side effect that I have to
take care ?


No, this seems fine.

The main thing you need to look for is "dangling references" that
can occur when objects retain references to other objects, while
the latter objects have been destroyed. That is not the case in
the presented code: 'dest' gets destroyed before 'logger'.

V
Nov 22 '05 #2

P: n/a
Looks okay to me. Your syntax looks fine.
I can't think of any problems with the way your using it since when
logger goes out of scope so does dest.

Nov 22 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.