Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

interface

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);
like image 614
Coder Avatar asked Feb 14 '12 23:02

Coder


People also ask

Can a derived class reference to base class object?

Yes, this is the answer.

Can you assign a derived class object to a base class object?

Object Slicing in C++ In C++, a derived class object can be assigned to a base class object, but the other way is not possible.

Can a derived class be a friend of a base class?

Inheritance and Friendship in C++ Difference between Inheritance and Friendship in C++: In C++, friendship is not inherited. If a base class has a friend function, then the function doesn't become a friend of the derived class(es).

Can base class access members of derived class give reasons?

Explanation: A base class pointer can point to a derived class object, but we can only access base class member or virtual functions using the base class pointer because object slicing happens when a derived class object is assigned to a base class object.


1 Answers

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.

like image 121
gwiazdorrr Avatar answered Oct 05 '22 21:10

gwiazdorrr