Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of typedef over derived class?

Simply put, what are the (or are there any) differences between doing say

class MyClassList : list<MyClass> { };

vs

typedef list<MyClass> MyClassList;

The only advantage that I can think of (and its what lead me to this question) is that with the derived class i can now easily forward declare MyClassList as

class MyClassList;

without compiler error, instead of

class MyClass;
typedef list<MyClass> MyClassList;

I can't think of any differences, but this made me wonder, are there cases in which a typedef can be used that a simple derived class can't?

Or to put it another way, is there any reason why I shouldn't change all my typedef list<...> SomeClassList; to the simple derived class so that I can easily forward declare them?

like image 572
MerickOWA Avatar asked Sep 02 '11 15:09

MerickOWA


2 Answers

In C++ it is NOT recommended to derive from an STL container, so don't do it.

A typedef is just creating an alias for an existing type, as it were, so typedef std::list<MyClass> MyClassList; creates a "new type" that is called MyClassList which you can now use as follows:

MyClassList lst;

Changing your typedefs to a derived class is a bad idea. Don't do it.

like image 57
Tony The Lion Avatar answered Sep 23 '22 09:09

Tony The Lion


typedef is intended exactly for this purpose -- to alias type names. Its very idiomatic and won't confuse anybody familiar with C++.

But to address why inheriting may be a bad idea.

std::list does not have a virtual destructor. Meaning MyClassList wouldn't have its destructor called when deleted through the base class. So this is typically frowned upon. In your case, you have no intention of putting any members in MyClassList, so this becomes a moot point until the next programmer sees inheritance as an invitation to add new members/override functions etc. They may not realize that std::list's destructor is not virtual and not realize that in some cases MyClassList's destructor won't get called.

like image 34
Doug T. Avatar answered Sep 19 '22 09:09

Doug T.