Hello all,
I am learning c++ and one of the samples I saw had the following function declaration.
Myfunc::Myfunc (char *parent)
: sample(parent, win_id)
{
some initializations etc.
};
Can some body explain this format. It is clear that Myfunc is a constructor but I am not clear on the ": function name" format. What is this format? Thank you.
It's an initializer list, used to initialize object data and base classes before the object is actually constructed. For details, see your favourite beginner's C++ book on it.
Hello,
Thank you very much for your reply, but I could not locate this kind of initialization example in c++ books I have referred. Is there any nomenclature for this? If there is please let me know so I will be able to locate in C++ books. Thanks once again.
I don't know how much help this will be, but I have only seen and used that notation when I have the constructor of a derived class, and I need the constructor of the base class to be called.
For example:
[code=c++]
BaseClass::BaseClass( int x ) {
// base class constructor code
}
DerivedClass::DerivedClass( int x, double y )
: BaseClass( x ) { // this line call the base class constructor
// constructor code goes here for derived class
}
[/code]
Hello Mahlerfive,
Thank you for your reply. Your reply did help me get the basic idea. Does this also mean that there must be same or more number of arguments in the derived class as the arguments in the derived class are passed to the base class.
When one is searching for this kind of constructs (either on the web or in books), what is the name/nomenclature to be used?
Required for:
- (non default) base class constructors
- const initialization
- reference initialization
"Recommended" for (there might be arguments about that, though):
- everything else that can be initialized in a class, especially
- ressource acquisition & initialization