I am writing a library in C++, and was wondering about the use of references and/or pointers in place of the interfaces (i.e., use of (abstract) base classes as a placeholder for derived classes).
The question is, which one of the two should I go for? Should I prefer one to another, at all? Is there any difference to using references to (abstract) base classes instead of pointers?
Please have a look at the below code excerpt, and comment on any issues:
#include <iostream>
class Base {
protected:
public:
virtual void Print() const {
std::cout << "Base" << std::endl;
}
};
class Derived : public Base {
protected:
public:
void Print() const override {
std::cout << "Derived" << std::endl;
}
};
class AnotherDerived : public Base {
protected:
public:
void Print() const override {
std::cout << "Another Derived" << std::endl;
}
};
void someFunc( const Base& obj ) {
obj.Print();
}
void anotherFunc( const Base* obj ) {
obj->Print();
}
int main( int argc, char* argv[] ) {
Base baseObj, *basePtr;
Derived derivedObj;
AnotherDerived anotherDerivedObj;
someFunc( derivedObj );
anotherFunc( &derivedObj );
someFunc( anotherDerivedObj );
/* slicing ??? */
baseObj = derivedObj;
/* another slicing ??? */
baseObj = anotherDerivedObj;
/* proper use */
basePtr = &anotherDerivedObj;
someFunc( baseObj );
anotherFunc( basePtr );
return 0;
}
I guess, in the above code, I am doing an object-slicing when copy-assigning a child object to a parent. However, assuming I am not doing any object-slicing (as in the first two calls to someFunc
), will the reference approach do what I am intending to do? Do both the reference and the pointer approaches internally use dynamic_cast
ing when deciding on which polymorphic function to call? Or, am I totally missing the point here?
Thanks in advance for your time!