Thread: What does this mean?

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    36

    What does this mean?

    http://www.devx.com/cplus/Article/28105/0/page/3

    Look at this page. On one of the lines, the code is
    Code:
    String::String(): pimpl (new String::StringImpl) {}
    What does this mean? It seems to assign a new StringImp to the pimpl variable, but what is the difference between the above code, and this:
    Code:
    String::String()
    {
     pimpl=new String::StringImpl
    }
    What exactly does the colon after the constructor do?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    The first example illustrates initialisation of a member variable using an initialisation list. The second example illustrates assignment to a member variable in the constructor body. For a pointer type there should be effectively no difference in efficiency, but for some class types the first example would be more efficient since the second might involve an expensive default initialisation followed by an expensive assignment.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    The initializer list will initialize objects in that it calls the constructor directly.
    If you try to assign in the body, it will first call the default constructor and then call operator = to assign a new String::StringImpl.
    In this case, as laserlight points out, it doesn't really matter which way you do it. But when it comes to more complex objects, it might be better to initialize it since it would save the time it takes to construct it and then assign. And also, if an object does not have a default constructor (a constructor that takes no arguments), then you must use initializer lists to pass the correct arguments to the correct constructor of the object.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed