Consider the following code:
class Abstract{
public:
virtual void printStuff()=0;
};
class Derived: public Abstract{
public:
void printStuff(){
printf("Stuff\n");
}
};
Now, let's say I want to create a function that uses the printStuff method from Abstract class. Before I learned that only one way is possible in C++, I thought that there would be two ways: the less obvious with pointers, and the more obvious, similar to what you would expect to do with ints, chars, etc.:
void ptr_function(Abstract* abs){ //non-obvious
abs->printStuff();
}
void non_ptr_function(Abstract abs){ //obvious, analogous to, say, pow(a,b)
abs.printStuff();
}
Now, I understand that the second one is forbidden in C++. However, I don't really understand the underlying reason for such design. Don't the above functions look identical, aside from the pointer vs. actal object being passed as an argument?
As a follow-up question: what is the preferred way to build classes that have to "contain" other, abstract, classes as one of the fields? If the answer to this question is also: "pointers", then am I missing something, or do I have to keep track of those objects' timelife myself (i.e. deleting them manually)? For non-abstract classes this is not an issue, as if I don't use pointers, then whenever that object gets out of scope, it gets automatically deleted (destructors called and so on). But if I have to use pointers, it looks like that micro-management takes a lot of unnecessary time and code.
Is there any better way to approach this?