Lecture No.11              

Problem:
Suppose we have requirement to change the class Student such that a student is given a roll number when the object is created and cannot be changed afterwards our existing class is given below,

Student Class

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



Solution of this problem:

We can do this by making rollNo constant so that cannot be changed once it is defined as shown below,


Modified Student Class
class Student{
            const int rollNo;
public:
            Student(int aNo);
            int getRollNo();
           
};



Now there is only one issue of initializing this roll no with initial value but the problem is that we cannot set the value of roll no in constructor, as when code in constructor is executed the data member roll no has already been created and when we try to assign value to it in constructor compiler generates error,
Example
Student::Student(int aRollNo)
{
            rollNo = aRollNo;
           
 /*error: cannot modify a constant data member assignment statement not initialization*/
}



Second solution is to write separate function but the problem remains same that we can’t assign value to constant data member,

void Student::SetRollNo(int i)
{
            rollNo = i;
            /*error: cannot modify a constant data member again assignment statement not initialization */
}



We also know that we can only declare data members in structure or class but we cannot initialize them at the time of declaration in structure or class _____ because before executing constructor code, the class const member roll no has not got life it will get life along with other class members when constructor will be invoked so we can not assign any value to this constant member while declaring it. [1]
Solution:
so what is the solution of this problem as we can not initialize constant members while declaring them and we can not initialize them in constructor also because as soon as they go life they become constant to solve this problem C++ gives us new mechanism (syntax) for initialization of constant data members of the structure or class to resolve above mentioned issues,


Initialization is assigning value along with creation of variable.

int i = 2;

Assignment is assigning value after creation.
int i;
i  = 7;



Member initialization list is used where we cannot modify the state of data members in the member functions of the class including constructor,

·         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 than one member use comma separated list

Example
class Student{
            const int rollNo;
            char *name;
            float GPA;
public:
            Student(int aRollNo) : rollNo(aRollNo), name(Null), GPA(0.0){ // initialization
                       
            }
};



Order of Initialization

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


Example
class ABC{
            int x;
            int y;
            int z;
public:
            ABC();
};
ABC::ABC():y(10),x(y),z(y)
{
           
}
/*         x = Junk value
                        y = 10
                        z = 10  */







·         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

#include <cstdlib>
#include <iostream>

using namespace std;


class Student{
            int rollNo;
public:
      
    Student( ) {
           
            }
     
            int getRollNo(){
                        return rollNo;
            }         
};


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

            //error 

  system("PAUSE");
    return EXIT_SUCCESS;
}

#include <cstdlib>
#include <iostream>

using namespace std;


class Student{
            int rollNo;
public:
      
    Student(int aRollNo) : rollNo(aRollNo){
           
            }
     
            int getRollNo(){
                        return rollNo;
            }         
};

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

    system("PAUSE");
    return EXIT_SUCCESS;
}


const Objects

const objects can access only const member functions so chances of change of state of const objects once they are created are eliminated.
We make getRollNo function constant so that we can access it using constant objects,

Example
class Student{
            int rollNo;
public:
            int getRollNo()const{
                        return rollNo;
            }          
};
int main(){
            const Student aStudent;
            int a = aStudent.getRollNo();
}


Constant member functions

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

Static variables of a class are such variables which are independent of class objects.

Lifetime of static variable is throughout the program life, if static variables are not explicitly initialized then they are initialized to 0 of appropriate type.

Example

Static variable is initialized once only throughout the program, independent of how many times the function initializing it is called, 

void func1(int i){
            static int staticInt = i;
//initialization statement will be executed once
//only as static variables are initialized once
            cout << staticInt << endl;
}
int main(){

Output:
1
1
 
            func1(1);
            func1(2);
}



void func1(int i){

 static int staticInt;
 staticInt = i;
//assignment statement will be executed with each function call
 cout << staticInt << endl;

}
int main(){

Output:
1
2
 
            func1(1);
            func1(2);
}

Static Data Member

Definition
“A variable that is part of a class, yet is not part of any object of that class, is called static data member”

Static Data Member

They are shared by all instances (objects) of the class
They do not belong to any particular instance of a class

Class vs. Instance Variable

Suppose we created three objects of student class as shown below,
Student s1, s2, s3;


Static Data Member (Syntax)

Keyword static is used to make a data member static

class ClassName{
static DataType VariableName;
};

Defining Static Data Member

Static data member is declared inside the class
But they are defined outside the class

Defining Static Data Member

class ClassName{
static DataType VariableName;
};

DataType ClassName::VariableName;
Initializing Static Data Member

Static data members should be initialized once at file scope
They are initialized at the time of definition

Example
class Student{
private:
static int noOfStudents;
public:
 
};
int Student::noOfStudents = 0;
/*private static member cannot be accessed outside the class except for initialization*/


Initializing Static Data Member

If static data members are not explicitly initialized at the time of definition then they are initialized to 0

Example

int Student::noOfStudents;

is equivalent to

int Student::noOfStudents=0;



In c++  static const data members can be initialized in class or structure as well.

1 Comments

Don't Forget To Join My FB Group VU Vicky
THANK YOU :)

  1. sir or b subjects k lecture upload karen plz

    ReplyDelete

Post a Comment

Don't Forget To Join My FB Group VU Vicky
THANK YOU :)

Previous Post Next Post