typedef vs. class definition

J

jsanga

What are the major benifits / drawbacks to the following code?

myheader.h

#include <vector>
struct MyStruct {
int f1;
float f2;
...
};

typedef std::vector< MyStruct > STRUCTURES;
class STRUCTURES_TOO : public std::vector< MyStruct > {};

The reason for asking is; I'm trying to reduce header file includes,
improve compile time and write better conforming code. The issue here
is when other classes need to pass around STRUCTURES as a parameter, I
am forced to include "myheader.h" for the definition.

anotherheader.h
#inlcude "myheader.h"
class MyClass {
public:
DoSomething( const STRUCTURES &s ); // require myheader.h
};

However, by declaring STRUCTURES_TOO I am able to do the following

anotherheader.h

class STRUCTURES_TOO; // Just forward ref the class
class MyClass {
public:
DoSomething( const STRUCTURES_TOO &s );
};

I know the STL doesn't have virtual destructors, so derrived classes
are frowned upon. But in this case I don't have the problem of passing
around base classes.
 
J

Jonathan Mcdougall

What are the major benifits / drawbacks to the following code?

These are not equivalent. You cannot and should not try to replace one
by the other, it makes no sense.
myheader.h

#include <vector>
struct MyStruct {
int f1;
float f2;
...
};

typedef std::vector< MyStruct > STRUCTURES;
class STRUCTURES_TOO : public std::vector< MyStruct > {};

The reason for asking is; I'm trying to reduce header file includes,
improve compile time and write better conforming code. The issue here
is when other classes need to pass around STRUCTURES as a parameter, I
am forced to include "myheader.h" for the definition.

Separate the typedef from the class definition.
anotherheader.h
#inlcude "myheader.h"
class MyClass {
public:
DoSomething( const STRUCTURES &s ); // require myheader.h
};

No, it requires the typedef and the typedef only requires a declaration
of the class.
However, by declaring STRUCTURES_TOO I am able to do the following

anotherheader.h

class STRUCTURES_TOO; // Just forward ref the class
class MyClass {
public:
DoSomething( const STRUCTURES_TOO &s );
};

You're using inheritance not because it suits your design, but because
you want to reduce compiling time. That's a bad choice, imho, and it's
worst because there are other ways.
I know the STL doesn't have virtual destructors, so derrived classes
are frowned upon.

Not if it suits your design.
But in this case I don't have the problem of passing
around base classes.


Jonathan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top