62

Say we have an abstract base class IBase with pure virtual methods (an interface).

Then we derive CFoo, CFoo2 from the base class.

And we have a function that knows how to work with IBase.

Foo(IBase *input); 

The usual scenario in these cases is like this:

IBase *ptr = static_cast<IBase*>(new CFoo("abc")); Foo(ptr); delete ptr; 

But pointer management is better to be avoided, so is there a way to use references in such scenario?

CFoo inst("abc"); Foo(inst); 

where Foo is:

Foo(IBase &input); 
4
  • 3
    Yes, what you have in your question is ideal. Commented Feb 14, 2012 at 23:15
  • 64
    Yes; polymorphism works for both pointers and references. And stop casting, please. We're not in Hollywood. Commented Feb 14, 2012 at 23:17
  • 1
    Now I know why it is called casting... seriously! Commented Nov 13, 2018 at 9:38
  • @KerrekSB Well you'd have to cast if you tried IBase& b = CFoo(); Commented Nov 8, 2021 at 4:18

2 Answers 2

66

Yes. You don't have to upcast your objects. All references/pointers to derived types are converted implicitly to base objects references/pointers when necessary.

So:

IBase* ptr = new CFoo("abc"); // good CFoo* ptr2 = static_cast<CFoo*>(ptr); // good CFoo* ptr3 = ptr; // compile error CFoo instance("abc"); IBase& ref = instance; // good CFoo& ref2 = static_cast<CFoo&>(ref); // good CFoo& ref3 = ref; // compile error 

When you have to downcast you may want to consider using dynamic_cast, if your types are polymorphic.

Sign up to request clarification or add additional context in comments.

2 Comments

I found where my problem was. I was using Foo(CFoo("abc")); which was not compiling.
@Coder : In case you're not aware, the reason that's a problem is because you're passing Foo an rvalue, and rvalues cannot bind to non-const lvalue references (i.e., if Foo were Foo(IBase const& input); instead, it would have compiled).
-1

You can cast an object just as you can a pointer. I remember this was common when converting char to unsigned char and various other sign changing casts in days of yore.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.