0

While reading some stuff on the pImpl idiom I found something like this:

MyClass::MyClass() : pimpl_( new MyClassImp() )

First: What does it mean?
Second: What is the syntax?
Sorry for being such a noob.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
da_petcu21
  • 527
  • 4
  • 15
  • 3
    Constructor initializer lists is a basic feature of C++ language. That's something you read about in your basic C++ book, not ask questions about on SO. – AnT stands with Russia Nov 22 '09 at 20:14
  • sorry, I am new to C++, I come from the C world. I am familiar to OOP from Obj-C and Delphi, but that was C++ specific. – da_petcu21 Nov 22 '09 at 20:22
  • Then do yourself a favor and read a basic introduction to C++. As Andrey said, this is _very_ basic knowledge. You cannot effectively learn the language without getting a basic introduction. – sbi Nov 22 '09 at 20:25

3 Answers3

8

This defines the constructor for MyClass.

The syntax is that of a constructor definition with an initialization list (I assume there is a set of braces following this that define the body of the constructor).

The member pimpl_ of MyClass is being initialized as a pointer to a new object of type MyClassImp. It's almost the same as the following:

MyClass::MyClass()
{
    pimpl_ = new MyClassImp();
}

However, it is preferable to use the initialization list for initializing class members wherever possible; see the C++ FAQ Lite entry linked above.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
2

It's an initialization list. It allow you to set the values of member and base class constructor before the constructor code is called.

You should use it to initialize the values of your class instance.

Klaim
  • 67,274
  • 36
  • 133
  • 188
0

In addition to being a constructor with an initialiser list as others have already explained, it's also using the private implementation pattern.

C++ requires the class declaration to include all the public and private members of the class. This can result in you having to expose implementation details that you don't want to, and to making your implementation part of your API/ABI. It can also significantly increase compile times due to additional #includes in the public headers to support the private member variables.

Making a second class with the actual implementation and just exposing the functional API makes this much cleaner, but at the cost of an additional layer of indirection.

C generally handles this by having a pointer to an opaque object which the library creates and destroys for you.

Malcolm
  • 1,239
  • 1
  • 14
  • 25