Initializing class member variable with reference

C

chris

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.
 
V

Victor Bazarov

chris said:
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
 
K

Kwan Lim

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top