Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

c++ - Is it possible to pass derived classes by reference to a function taking base class as a parameter

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...