Lecture 6 Scope Static Constants
Lecture 6 Scope Static Constants
Programming
C++
Scope Rules Static Class Members
Static Member Functions
Constant Variables
1
Outline
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);
10
Default Copy Constructors
• The default copy constructor is fine for simple
classes
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
// Modify obj2
obj2.value = 100;
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.
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 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;
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
// 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();
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
};
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.
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
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;
public:
MyClass(int v) : value(v) {}
void modifyValue(int v) {
value = v;
}
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.
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.