Home C++ Introduction Decisions Loops Input/Output Functions Stack and Heap References Arrays Searching and Sorting Recursion Pointers Character and Strings Structures Classes Inheritance Exceptions Templatess STL Modern C++ Misc Books ----

Classes


Contents

Initialization Lists

There are times when data members need to be initialized but we can't do it in the class itself. C++ has a special mechanism to handle that and that is the initialization list.
File: init1.cpp
#include <iostream>
using namespace std ;

class engine
{
    public:
    int cyclinders ;
    engine()
    {
    }
    engine(int cyclindersP )
    {
        cyclinders = cyclindersP ;
    }
};

class car
{
    public:
    const int someConstant ;
    int& someReference ;
    engine engineObj ;
    car(int x1, int x2 , int x3 ) :
    someConstant(x1) , someReference(x2),
    engineObj( x3 )
    {
        //someConstant = x1 ;
        // engineObj( x3) ;
        someReference = 10 ;
    }
};

int main()
{
    car carObject( 1 , 2 , 3 ) ;
    cout << carObject.engineObj.cyclinders << endl ;
    return(0) ;
}


Exercise
1)
File: init_ex1.cpp

Friend

Const functions

OO

Smart Pointer