const keyword

Posted on April 18, 2013. Filed under: C++ |


const keyword can declare variables that can not change. If you have a const variable in your class, you have to use member initializers to initialize them in the class constructor.

class Sally

{

public:

Sally(int a, int b); //constructor takes 2 variables, one assign to regVar, another to constVar

private:

int regVar;   //regular variable

const int constVar;  //constant variable

}

=========================================

#include “Sally.h”

#include <iostream>

using namespace std;

Sally::Sally(int a, int b)  //constructor takes two parameters

: regVar(a),           //: tell c++ I will start a member initializer list, use comma as separator

constVar(b)         //const variable have to be initialized with this weird member initializer syntax

{} //no code here because const variable can’t be initialized in normal way.

====================================

Sally so(3,87); //caller assigned 3 to regVar, 87 to constVar.

const keyword allows C++ to create both ordinary objects and constant objects from a class containing both regular functions and constant functions. The constant object can not be modified.

Whenever you create a const object, you tell the compiler the object can not be modified, you can only access the constant members defined inside the class.

The syntax for const object is as follows.
in class body:
void Sally::printShiz2() const {
cout << ‘whatever’ << endl;
}

in header prototype:
void printShiz2() const;

in caller:
const Sally constObj;
constObj.printShiz2();

Advertisements

Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Liked it here?
Why not try sites on the blogroll...

%d bloggers like this: