Cpp - Passing object a const Pointer

Introduction

When passing object by a const pointer, compiler prevents calling any non-const member function on the object, and thus protects the object from change.

Demo

#include <iostream> 
   //from   w  ww .  java 2  s .c om
class Bug 
{ 
public: 
    Bug(); 
    Bug(Bug&); 
    ~Bug(); 
   
    int GetAge() const { return itsAge; } 
    void SetAge(int age) { itsAge = age; } 
   
private: 
    int itsAge; 
}; 
   
Bug::Bug() 
{ 
    std::cout << "Simple Bug Constructor ..." << std::endl; 
    itsAge = 1; 
} 
   
Bug::Bug(Bug&) 
{ 
    std::cout << "Simple Bug Copy Constructor ..." << std::endl; 
} 
   
Bug::~Bug() 
{ 
    std::cout << "Simple Bug Destructor ..." << std::endl; 
} 
 
const Bug * const  
FunctionTwo (const Bug *const theBug); 
   
int main() 
{ 
    Bug bug; 
    std::cout << "bug is "; 
    std::cout << bug.GetAge() << " years old" << std::endl; 
    int age = 5; 
    bug.SetAge(age); 
    std::cout << "bug is "; 
    std::cout << bug.GetAge() << " years old" << std::endl; 
    FunctionTwo(&bug); 
    std::cout << "bug is "; 
    std::cout << bug.GetAge() << " years old" << std::endl; 
    return 0; 
} 
   
// functionTwo, passes a const pointer 
const Bug * const  
FunctionTwo (const Bug * const theBug) 
{ 
    std::cout << "Function Two. Returning ..." << std::endl; 
    std::cout << "bug is now " << theBug->GetAge(); 
    std::cout << " years old \n"; 
    // theBug->SetAge(8); const! 
    return theBug; 
}

Result

Related Topic