Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I'm pretty sure this is a question purely about aesthetics but I wanted to get all your opinions on it before I start proliferating this type of code in my codebase. Consider the following code:

//Foo.h
class Bar;
class Foo
{
    public:
       Bar& GetBar(){return *bar.get();}
    private:
       std::unique_ptr<Bar> bar;
};

//Bar.h
class Bar
{
     public:
         DoSomething(){//did something...}
};

This allows us to forward declare Bar in Foo.h and avoid having to #include Bar.h. This leads to using Foo's Bar in the following way:

Foo foo;
foo.GetBar().DoSomething();

Personally, I think this would look a lot nicer:

Foo foo;
foo.bar.DoSomething();

To achieve that, I've written:

//Foo.h
class Bar;
class Foo
{
    public:
        Foo();
        Bar& bar;
    private:
        std::unique_ptr<Bar> bar_ptr;
};

//Foo.cpp
#include "Bar.h"
Foo::Foo() : bar_ptr(new Bar()), bar(*bar_ptr) {}

This allows me to forward declare Bar and use the 'bar.' syntax.

Ugly? Not Ugly? The downside is that I have 2 member vars for only 1 object.

share|improve this question
add comment

2 Answers

up vote 5 down vote accepted
foo.GetBar().DoSomething();

This violates the Law Of Demeter.

Generally I would avoid exposing Bar entirely:

foo::doBarSomething() { this->bar.doSomething(); }
share|improve this answer
    
+1 and in this case no longer worry about unique_ptr, and then use the simpler shared_ptr –  Stephane Rolland Apr 17 '13 at 15:40
4  
How is shared_ptr more simple than unique_ptr? –  bstamour Apr 17 '13 at 19:24
add comment

I don't think it's ever a good idea to use a reference as a class member.

If you use a reference, you are required to define the object that it references to in the constructor, and you can never again change the object that that reference points to again. Consequently, you'll have serious problems if you ever call bar_ptr.reset() and try to access bar.

Also, using a reference the way you are using is essentially the same as declaring Bar as a public non-pointer variable. I honestly don't see a reason for all that inconvenience just so you don't have to do an #include on a header.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.