Sign in to follow this  
storage

Naming and namespaces

Recommended Posts

Lets say I'm developing a library, how should I name the classes for readability and reusability? Should I use namespaces, or are there any negative effects due to the use of them? Lets say the acronym for the library is LIB, which do you think "looks better"?
namespace LIB
{
    class Base
    {
    };
    
    class Derived : public LIB::Base    // Another question, is it necessary to write LIB::?
    {
    };
}

// OR ... 

class LIBBase
{
};

class LIBDerived : public LIBBase
{
};

I'm sure this has been asked and answered before, but while I'm writing I might aswell ask. Lets say I have an object, that I know is of the class Word, how do I figure out if the object is really the class Hello, that is derived from class Word? Thanks in advance :)

Share this post


Link to post
Share on other sites
Consider this another vote for namespaces. Yeah, namespaces!

Also, for readability, I've often seen the coding standard that acronyms be written like they're not acronyms, i.e. Lib instead of LIB, or Xml instead of XML.

And for your second question, you have two basic options:

1) Use C++'s RTTI (Run-Time Type Information). This can provide you the details on the actual type of the object. Google "RTTI" along with "determining base and derived classes" and I'm sure you'll find some details on the specifics. Personally, I can't provide any 'cause I don't use/like RTTI...

2) Which means you do essentially "lightweight" RTTI. Which means that you add a member to the base class that derived classes set to indicate their type. Yes, RTTI may be able to do this more efficiently, but this is more transparent and tunable in the long term. For example:


class Base
{
virtual int GetType() { return 0; }
};

class Derived : Base
{
virtual int GetType() { return 1; }
};

class FurtherDerived : Base
{
virtual int GetType() { return 2; }
};



You could then call myBaseObject.GetType() and then do a switch to determine the type.

Of course, this would be a horrible thing to do in *most* situations. It is usually an indicator of a problem in the design.

The whole point of inheritance and polymorphism is to eliminate situations where you write code that "switches on type." Anytime you find yourself making a decision based on querying the type of something, stop and ask yourself, "Should this be a virtual function somewhere?" The answer is usually, "Yes."

I'd recommend that if you have a particular scenario in mind that you start a new thread with the specific scenario as it'll likely get lost under this thread's subject.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this