Advertisement

Question about an odd function declaration

Started by March 30, 2001 03:26 PM
0 comments, last by Dark Rain 23 years, 10 months ago
I''ve been reading a book that use this kind of declaration all over the place :

plane3( const point3& N, float D) : n( N ), d( D )
{
	// CODE HERE.
}
 
It''s the ": n( N ), d( D )" part that bother me. I''ve been asking around but no one I know could tell.
The stuff after the colon is used to initialize the class. Let me explain a bit further. As you know, classes have constructors, many of which take parameters to initialize the object. For consistency, C++ allows you to use a similar syntax for built-in types, too. Anyway, let's say you have a class with 2 members you have to initialize, one an int and one a char*. This is one way to initialize your class:

  class blah{    public:        blah()        {            i = 12;            str = "blah!";            // more stuff        }    private:        int i;        char* str;};  


And here's the preferred method:

  class blah{    public:        blah(): i(12), str("blah!")            {/* more stuff */}    private:        int i;        char* str;};  


In a simplistic sense, they both do the same thing: they initialize members. There's another use for this stuff. If your class is derived from some other class and that parent class has a certain constructor that needs to be called, use the initialization syntax for that also. For example:

  class base{    public:        base(int i_val, const char* i_str): i(i_val), str(i_str)        {/* more stuff */}    private:        int i;        char* str;};class child: public base{    public:        child(): base(12, "hello!")        {/* more stuff */}    private:        // perhaps some more stuff};  


That's about it. One thing to keep in mind is that you only use the initialization list where the function is actually implemented. So, if you implement it in a source file, it goes there and not in the header. If it's implemented in the header and not a source file, it goes in the header. Oh...and, of course, you can only do this with constructors.

Hope that helps.


Edited by - merlin9x9 on March 30, 2001 4:49:48 PM

This topic is closed to new replies.

Advertisement