Docsity

OOP Lecture 11: Const Objects, Static Vars, and Member Init List, Slides of Object Oriented Programming

Partial preview of the text

Download OOP Lecture 11: Const Objects, Static Vars, and Member Init List and more Slides Object Oriented Programming in PDF only on Docsity!

Object Oriented Programming

(OOP)

Lecture No. 11

Review

  • this Pointer
  • Separation of interface and implementation
  • Constant member functions

Student Class

class Student{ … int rollNo; public: Student(int aNo); int getRollNo(); void setRollNo(int aNo); … };

Modified Student Class

class Student{ … const int rollNo; public: Student(int aNo); int getRollNo(); void setRollNo(int aNo); … };

Example

void Student::SetRollNo(int i)

{

rollNo = i; /error: cannot modify a constant data member/

}

Member Initializer List

  • A member initializer list is a

mechanism to initialize data members

  • It is given after closing parenthesis of

parameter list of constructor

  • In case of more then one member

use comma separated list

Order of Initialization

  • Data member are initialized in order they are declared
  • Order in member initializer list is not significant at all

Example

class ABC{

int x;

int y;

int z;

public:

ABC();

const Objects

• Objects can be declared

constant with the use of const

keyword

• Constant objects cannot

change their state

Example

int main()

{

const Student aStudent; return 0;

}

Example

int main(){

const Student aStudent; int a = aStudent.getRollNo(); //error

}

const Objects

  • const objects cannot access

“ non const” member function

  • Chances of unintentional

modification are eliminated

Example

int main(){

const Student aStudent; int a = aStudent.getRollNo();

}

Constant data members

  • Make all functions that don’t change the state of the object constant
  • This will enable constant objects to access more member functions