How to use "const". Part 1

How to use "const". Part 1

There is a lot of information about this subject on the Internet.

 

They are been confused very easy when you didn't use them long time.

 

So I just collated and tidied.

 

 

	#include "stdafx.h"

extern void AppPause();


class Parent
{
public:
    Parent():_iCount(0){};

    void Add()
    {
        ::printf("%d\n", ++_iCount);
    }

private:
    int _iCount;
};


class SubA : public Parent
{
public:
    SubA(){};
};


class SubB : public Parent
{
public:
    SubB(){};
};


int _tmain(int argc, _TCHAR* argv[])
{
    const Parent* pParent1 = new SubA();
    pParent1 = new SubB();    // It could be compiled, but it was caused memory leak in the SubA.
    pParent1->Add();        // It couldn't be compiled, because the memory content couldn't be modified.
    delete pParent1;
    

    
    Parent const *pParent2 = new SubA();
    pParent2 = new SubB();    // It could be compiled, but it was caused memory leak in the SubA.
    pParent2->Add();        // It couldn't be compiled, because the memory content couldn't be modified.
    delete pParent2;
    
    
    
    Parent* const pParent3 = new SubA();
    pParent3 = new SubB();    // It couldn't be compiled, because the memory address couldn't be modified.
    pParent3->Add();        // It could be compiled.
    delete pParent3;


    
    const Parent* const pParent4 = new SubA();
    pParent4 = new SubB();    // It couldn't be compiled, because the memory address couldn't be modified.
    pParent4->Add();        // It couldn't be compiled, because the memory content couldn't be modified.
    delete pParent4;
    


    const Parent const *pParent5 = new SubA();
    pParent5 = new SubB();    // It could be compiled, but it was caused memory leak in the SubA.
    pParent5->Add();        // It couldn't be compiled, because the memory content couldn't be modified.
    delete pParent5;
    


    AppPause();

    return 0;
}


void AppPause()
{
    char cPause;    
    do    
    {        
        cPause = getchar();        
        if(cPause == EOF)            
            break;    
    } while(cPause != '\n');
}
Allow me make a summary.
 
The memory address could be modified, but the memory content couldn't be modified.
const Parent* pParent1 = new SubA();

The memory address could be modified, but the memory content couldn't be modified.
Parent const *pParent2 = new SubA();

The memory content could be modified, but the memory address couldn't be modified.
Parent* const pParent3 = new SubA();

The memory address and the memory content could neither be modified.
const Parent* const pParent4 = new SubA();

The memory address could be modified, but the memory content couldn't be modified.
const Parent const *pParent5 = new SubA();