0% found this document useful (0 votes)
4 views

Lecture 6 Scope Static Constants

Uploaded by

ehsaan ershaad
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lecture 6 Scope Static Constants

Uploaded by

ehsaan ershaad
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 82

CS212 – Object Oriented

Programming
C++
Scope Rules Static Class Members
Static Member Functions
Constant Variables

Dr. Muhammad Sadiq Amin

1
Outline

• Last Lecture Remaining


content
• Scope Rules
– Local Variable
– Global Variables
• Static Variables
• Static Class Members
• Static Member Functions
• Constant Variables
2
Constructors Example

3
Initialization List
• When a constructor is used to initialize other members, these
other members can be initialized directly, without resorting
to statements in its body.
• This is done by inserting, before the constructor's body, a
colon (:) and a list of initializations for class members. For
example, consider a class with the following declaration:

4
Initialization List

5
Initialization List Example
Class Distance
{
private:
int feet;
Class Distance
float inches
public:
{
Distance(){ private:
feet=0; int feet;
inches = 0.0; float inches
} public:
Distance() : feet(0), inches(0.0)
};
{}
};
Initialization List Example
Class Distance
{
private:
int feet;
float inches Class Distance
public: {
Dista private:
nce(i int feet;
nt ft,
float float inches
in){ public:
feet = ft; Distance(int ft, float in): feet(ft), inches(in)
inches = in; {}
}
};
};
Initialization List Example
Class Distance
{
private:
int feet;
float inches Class Distance
public:
Dista
{
nce() private:
{ int feet;
feet=0;
float inches
inches = 0.0;
} public:
Distance(int ft, float in){
feet = ft; Distance() : feet(0), inches(0.0)
inches = in; {}
} Distance(int ft, float in): feet(ft), inches(in)
{}
} }
Copy constructor (Default)
void main()
{ Box B1(2, 4, 6);
Box B2(B1);

cout <<“volume of 1st box=“


cout <<
B1.cal_volume()<
<endl;

cout <<“volume of 2nd box=“


cout <<
B2.cal_volume();
}
OUTPUT
Box constructor called 9
Default Copy Constructors
• The compiler generates a default version of what is
referred to as a copy constructor.
• A copy constructor creates an object of a class by
initializing it with an existing object of the same
class.
• The default version of copy constructor creates
new object by copying existing object member by
member.
• You can use the copy constructor in this way for
any data types

10
Default Copy Constructors
• The default copy constructor is fine for simple
classes

• But for many classes that have pointer as


members may produce undesirable results

11
Example
#include <iostream>
using namespace std;
class Simple {
public:
int value;
// Constructor to initialize value
Simple(int v) : value(v) {}

// Display function
void display() {
cout << "Value: " << value << endl;
}
};
int main() {
Simple obj1(42); // Create an object of Simple
Simple obj2 = obj1; // Use the default copy constructor

// Display values of both objects


obj1.display(); // Output: Value: 42
obj2.display(); // Output: Value: 42

// Modify obj2
obj2.value = 100;

// Display values after modification


obj1.display();
obj2.display();
return 0;
}
Default Copy Constructors

13
Default Copy Constructors
Output??

20
Scope Rules
Lesson 1

3
Scope

A scope is a region of a
program
Scope of Variables
Broadly speaking there are three places,
where
variables can be declared −
• Inside a function or a block which are called
local variables.
• In the definition of function which are called
formal parameters/parameter-list.
• Outside of all functions which are called
global variables.
Local Variables
• They can be used only by statements that
are inside that function or block of code.

• Variables defined local to a function


disappear at the end of the function scope.

• Local variables are not known to functions


outside their own.
Local Variables – Example
#include <iostream>
using namespace std;

int someFunction()
{
int a, b; // Local variable declaration
int c;

Output
// initialization
a = 10;
b = 20;
c = a + b;
return c;
} error: 'a' was not declared in this scope
int main ()
error: 'b' was not declared in this scope
{
cout <<
someFunction(); cout
<< a << b;
Global Variables
• Defined usually on top of the program.
• Will hold their value throughout the life-time
of a program.
• Can be accessed by any function.
• Available outside the scope of the function, so
it can be accidentally changed.
Global Variables
#include <iostream>
using namespace std;

// Global variable declaration and


initialization int g = 20;

int main () Output


{ 20
cout << g;
return 0;
}
Global Variables – Example
#include <iostream>
using namespace std;

// Global variable
declaration int g;

int main ()
{ Output 30
// Local variable declaration
int a, b;

// Initialization
a = 10;
b = 20;
g = a + b;

cout << g;

return 0;
}
Global Variables – Example
#include <iostream>
using namespace std;

// Global variable declaration initialization


& int g = 10;

int main ()
{
// Local variable Output 30
declaration int a, b;

// Initialization
a = 10;
b = 20;
g = a + b;

cout << g;

return 0;
}
Global Variables – Example
#include <iostream>
using namespace std;

// Global variable
declaration int g = 10;

void display(int g) {
cout << g << endl; 10
} Output
10
int main () {
// Local variable declaration
30
int a, b;
cout << g <<
endl; display(g);

// Initialization
a = 10; b = 20;
g = a + b;
cout << g << endl;
}
Local & Global Variables – Naming

A program can have same


name for local and global
variables But
value of local variable inside a function
will take preference.
Global Variables – Example
#include <iostream>
using namespace std;

// Global variable
declaration int g = 10;

void display(int g) {
cout << g << endl;
} Output 9
9
int main () {
// Local variable declaration 30
int a, b;
int g=9;
cout << g <<
endl; display(g);

// Initialization
a = 10; b = 20;
g = a + b;
cout << g << endl;
Local
i=1
Variables
#include <iostream>
using namespace std; i=1
void func() { i=1
int i=0; i=1
cout << "i = i=1
" << ++i << i=1
endl;
i=1
i=1
Output i=1
} i=1
int main() {
for(int x =
Local and Global Variables
• When you call the function again, storage
for the local variables is created anew and
the values are re-initialized.
• If you want a value to be retained, you
can define a global variable.
• But variable is outside the
global available
scope the function, so it can be
inadvertently
of changed.
Global Variables
#include <iostream> i = 1
using namespace std; i = 2
int i=0; i = 3
void func() { i = 4
cout << "i = " << ++i i = 5
<< endl; i = 6
Output
} i = 7
int main() { i = 8
for(int x = 0; x < 10; i = 9
x++)
i = 10
func();
}
Static
Variables
Lesson 2

18
Static Variables
• To solve this issue we can create a
static variable and give it an initial value.
• The initialization is performed only the first
time the function is called, and the
data retains its value between function
calls. This way, a function can “remember”
some piece of information between function
calls.
• The second meaning of static is related to
the first in the “unavailable outside a
certain scope” sense.
Static Variables
• The beauty of a static variable is that it is
unavailable outside the scope of the function,
so it can’t be inadvertently changed.
This localizes errors.
• The second meaning of static is related to
the first in the “unavailable outside a
certain scope” sense.
Static
Variables
#include <iostream> i = 1
using namespace std; i = 2
void func() { i = 3
static int i=0; i = 4
cout << "i = " << ++i i = 5
<< endl; Output i = 6
} i = 7
int main() { i = 8
for(int x = 0; x < 10; i = 9
x++)
i = 10
func();
}
Class activity
#include <iostream>
using namespace std;

void counter() {
static int count = 0; // Static variable retains value between function calls
count++;
cout << "Count: " << count << endl;
}

int main() {
counter(); // First call, count = 1
counter(); // Second call, count = 2
counter();

cout << "Outside function: " << count << endl;


return 0;
}
Static variables with classes
• A static variable inside a class is shared among all
instances (objects) of that class.
• Unlike non-static members, which are unique to each
object, a static data member is common to all objects of
the class, meaning it has a single instance that is shared.
• Key Points About Static Variables in Classes:
• Shared among all objects: All instances of the class share
the same copy of the static variable.
• Exists independently of objects: You can access it without
creating an instance of the class, using
ClassName::variableName.
• Must be defined outside the class (if not const).
static qualifier in OOP
Lesson 3
1. Data member
2. Member function

22
Common Data
• What to do if you want to have some
data common or shared across ALL objects
in a class?
• For example, in StudentResult Class
• you want to keep track of how many
objects
have been created OR
• You want a data member that contains
the average percentage of all students.
• Or total number of students
Common Data
• We can define class members
static using static keyword
• No matter how many objects of the class
are created, there is only one copy of the
static member
• A static member is shared by all objects of the
class
Static Data Member
• If you want to have some data entity
common to or shared across every object of a
class, you make that data member
“static”

}
;
One copy shared by all objects

student1 student2 student3 student4


9 34 28 12
80 79 65 85
75 79 65 85
95 79 65 85
4
Scope of static data
• Static data members have class scope. It
is visible only within the class, but its lifetime
is the entire program.
• It continues to exist even if there are
no objects of the class.
Static Data Member
• Static members can be declared public,
private or protected.
• Static data member is initialized by default
to
0.
• If you want a different initial value, a
static
data member can be initialized once
Static Data Member

student1 student2 student3 student4


9 34 28 12 const
80 79 65 85
75 79 65 85
95 79 65 85
4 static
Static Data Member
• Static member data requires two
statements.
separate
– The variable’s declaration appears in
the
class definition
– but the variable is actually defined
outside
the class
Static Data Member Initialization
• All static data is initialized to zero when
the first object is created, if no other
initialization is present
• We can't put initialization in the
class definition but it can be initialized
outside the class
• Initialization is done by redeclaring the
static variable, using the scope
resolution operator :: to identify which
class it belongs to.
Static Data Member: Declaration
• The variable’s declaration appears in
the class definition

};
Static Data Member: Definition
• but the variable is actually
outside
defined
the class
};

};
Separate Declaration and Definition
• Why is this two-part approach used?
If static member data were defined
inside the class , it would violate the
idea that a class definition is only a
blueprint and does not set aside any
memory.
Accessing static data of a class
To access a public static class member when
no objects of the class exist, simply prefix the
class name and the binary scope resolution
operator (::) to the name of the data member.
Accessing static data of a class
• To access a private class member, you need
a member function.
• To access a private static class member,
you
need a static member function.
Static Member Functions
A static member function in a class is a function
that can be called without creating an object of
the class.
It operates on static data members of the class
and cannot access non-static members directly
because static functions are not associated with
any specific object.
Key Features of Static Member Func
Shared across all objects:
Static member functions are shared among all instances of the
class, just like static data members.

Cannot access non-static members: Static functions can only


access static data members and other static member functions.
They cannot directly access non-static data members or
functions.

Callable without an object: You can call a static member function


using the class name rather than an object.
Example
#include <iostream>
using namespace std;
class MyClass {
private:
static int count; // Static data member
public:
// Static member function to access private static data member
static void incrementCount() {
count++; // Can modify static members
}
// Static member function to return the static variable value
static int getCount() {
return count;
}
};

// Define and initialize static data member outside the class


int MyClass::count = 0;
int main() {
// Call static member functions without creating any objects
MyClass::incrementCount();
MyClass::incrementCount();
cout << "Count: " << MyClass::getCount() << endl; // Output: 2
return 0;
}
Const
Variables
Lesson 1

52
const using #define
#define PI 3.14159
• Everywhere you used PI, the value 3.14159
was substituted by the preprocessor
• For example it specifies that the identifier PI
will be replaced by the text 3.14159
throughout the program.
• not recommended in C++
const Variables
• C++ introduces the concept of a named
constant that is just like a variable, except
that
its value cannot be changed.
• The modifier const tells the compiler that a
name represents a constant.
• Any data type, built-in or user-defined,
may be
defined as const.
const Variables
• If you define something as const and then
attempt to modify it, the compiler will
generate an error.
• A const has a scope, just like a
regular variable,
const Variables
• The keyword const (for constant) precedes
the data type of a variable.
const int x = 10;
• It specifies that the value of a variable will not
change throughout the program.
• In C++, a const must always have
an initialization value
const Variables
• const qualifier is used to prevent variables
from being modified

• Any attempt to alter the value of a


variable defined with this qualifier will elicit
an error message from the compiler.

• Compiler error: cannot modify a constant


variable
const Variables Example
#include <iostream>
using namespace std;
const double pi = 3.14159 Output: 31.4159

int main ()
{ double r=5.0; // radius
double circle; circle = 2 * pi * r;
cout << circle;
}
const Variables Example
#include <iostream>
using namespace std;
#define PI 3.14159 Output: 31.4159

int main ()
{ double r=5.0; // radius
double circle; circle = 2 * PI * r;
cout << circle;
}
const qualifier in OOP
Lesson 2
1. Data member
2. Member function
3. Object

60
StudentResult Class
• Wha if I want that numbe
t
should not be
roll r
modified

}
;
const Data Member
• A data member whose value
cannot be modified, once
initialized.

}
;
Key Points about const member
Initialization:
• const data members cannot be assigned values inside the
constructor body or after the object is created.
• They must be initialized using the constructor initializer list.
Access and Usage:
• Once initialized, const data members cannot be modified.
• They are typically used for values that need to remain
constant throughout the object's lifetime, such as
configuration values.
Initializing a const Data Member
• const data members must be initialized
using
member initializer list

}
;
const data in all objects

const
student1 student2 student3 student4
9 34 28 12
80 79 65 85
75 79 65 85
95 79 65 85
2- const Member function
• A const member function guarantees that
it will never modify any of its data.
• Member functions that do nothing
but
acquire data from an are
candidates for being made
objectconst because
obvious
they
don’t need to modify any data.
3- const Object
• Any const member function that attempts
to change a member variable or call a non-
const member function will cause a
compiler error to occur.
2- const Member function
• Exampl
e
2- const Member function
• To declare a member function as const,
you need to add the keyword const at the
end of the function declaration.
3- const Object
• When an object is declared as
const, it cannot be modified
34
80
75
student1
95
83.33
A
3- const Object
• When an object is declared as
const, it cannot be modified
34
80
75
student1
95
83.33
A
3- const Object
• For any object that you declare to be
const, you can only call member functions
that are also declared to be const.
Example of Attempting to Modify Inside a Const
Function:
class MyClass {
private:
int value;
public:
MyClass(int v) : value(v) {}
// Const member function
void display() const {
cout << "Value: " << value << endl;

value = 100; // Error! Cannot modify a member variable in a const


member function
}
};
Example of Calling Non-const Functions from Const Functions (Error):
class MyClass {
private:
int value;

public:
MyClass(int v) : value(v) {}

void modifyValue(int v) {
value = v;
}

// Const member function


void display() const {
cout << "Value: " << value << endl;

modifyValue(100); // Error! Cannot call non-const member function from const


member function
}
};
Const summary
• A const member function ensures that the object’s state
remains unchanged.

• You should declare member functions const when they are


intended to read data from the object but not modify it.

• const objects can only call const member functions.

• Attempting to modify a member variable or calling a non-


const function inside a const member function will result in a
compile-time error.
Mutable Data
Members
Lesson 3

79
Mutable Data Members
• We may need to allow certain selected
data members of a class to be altered, even
if the object was declared as const.

• To accommodate such a situation you need to


be able to exempt a particular data member
from the const-ness of an object and you
need to be able to alter the value of the
exempt data member in a const member
function.

• You can do both by declaring a data member


as
Mutable Data Members: Program
1

Output
20
Mutable Data Members:Program 2

Output
error
constructors and destructors
• const can't be used for constructors
and destructors
• The purpose of a constructor is to
initialize field values, so it must change
the object. Similarly for destructors.
• This is because const objects should
initialize their member variables, and a
const constructor would not be able to do
so.

You might also like