0% found this document useful (0 votes)
3 views43 pages

OOP Lecture 4 - V2

The document discusses key concepts in C++ programming, focusing on member initialization lists, static data members, inline functions, and object arrays. It explains how to properly initialize class members, the characteristics and usage of static members, and the benefits of inline functions for performance optimization. Additionally, it illustrates the use of object arrays for managing collections of class instances efficiently.

Uploaded by

processingwait
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views43 pages

OOP Lecture 4 - V2

The document discusses key concepts in C++ programming, focusing on member initialization lists, static data members, inline functions, and object arrays. It explains how to properly initialize class members, the characteristics and usage of static members, and the benefits of inline functions for performance optimization. Additionally, it illustrates the use of object arrays for managing collections of class instances efficiently.

Uploaded by

processingwait
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 43

[CS1420]

L E C T U R E 4 : S TAT I C VA R I A B L E S A N D M E M B E R
FUNCTIONS, INLINE FUNCTIONS, OBJECT
A R R AY

Member initialization list/Array & constants, Static data and member


functions, Inline functions, Object Array

Engr. Syeda Aimen Naeem


[email protected]
MEMBER INITIALIZATION
LIST/ARRAY & CONSTANTS
MEMBER INITIALIZATION LIST
• Initializer List is used in initializing the data members of a class. In C++, initialization lists are
used to initialize class members before entering the constructor body.
• This is particularly useful when dealing with constant data members and arrays, as they must
be initialized at the time of object creation.
• The list of members to be initialized is indicated with constructor as a comma-separated list
followed by a colon. Following is an example that uses the initializer list to initialize x and y of
Point class.
MEMBER INITIALIZATION LIST
class Point { int main()
private: {
int x; Point t1(10, 15);
int y; cout << "x = " << t1.getX() << ", ";
public: cout << "y = " << t1.getY();
Point(int i = 0, int j = 0): x(i), y(j) {} return 0;
int getX() const { return x; } }
int getY() const { return y; }
};
INITIALIZATION LIST FOR NON-STATIC
CONST DATA MEMBERS
• const data members must be initialized using Initializer List.
• Reason for initializing the const data member in the initializer list is because no memory is
allocated separately for const data member, it is folded in the symbol table due to which we need
to initialize it in the initializer list.
• Also, it is a Parameterized constructor and we don’t need to call the assignment operator which
means we are avoiding one extra operation.
INITIALIZATION LIST FOR NON-STATIC
CONST DATA MEMBERS
class Test {
const int t; int main() {
public: Test t1(10);
//Initializer list must be used cout<<t1.getT();
Test(int t):t(t) {} return 0;
int getT() { return t; } }
};
INITIALIZATION LIST FOR ARRAY DATA
MEMBERS
• In C++, initializing arrays inside a constructor's member initializer list works differently than
initializing scalar members.
• C++ (older version, before 11) does not allow direct member initializer list initialization for
arrays in a constructor like this:
INITIALIZE ARRAYS IN A CONSTRUCTOR

(C++ Older Versions)


class Example { void print() {
int arr[3]; for (int i : arr) std::cout << i << " ";
public: std::cout << std::endl;
Example() { }
int temp[3] = {1, 2, 3}; // Temporary array };
for (int i = 0; i < 3; i++) { int main() {
arr[i] = temp[i]; // Copy values Example obj;
} obj.print(); // Output: 1 2 3
} }
INITIALIZATION LIST FOR ARRAY DATA
MEMBERS (Version 11 And Above)
class Example { void display() {
private: std::cout << "Array Values: ";
int arr[3]; for (int i = 0; i < 3; i++) {
public: std::cout << arr[i] << " ";}}};
Example(int x, int y, int z) : arr{x, y, z} {
// Constructor body int main() {
} Example obj(1, 2, 3);
obj.display();
return 0;}
INITIALIZER LIST
• Key Points:
• Constants (const members) must be initialized in the member initialization list.
• Arrays can be initialized using braces {} inside the initialization list.
• Using an initialization list is more efficient than assignment inside the constructor body.
S TAT I C D ATA M E M B E R S
& MEMBER FUNCTIONS
C++ STATIC DATA MEMBERS
Static data members are class members that are declared using static keywords. A static member
has certain special characteristics which are as follows:
• Only one copy of that member is created for the entire class and is shared by all the objects of
that class, no matter how many objects are created.
• It is initialized before any object of this class is created, even before the main starts outside the
class itself.
• It is visible can be controlled with the class access specifiers.
• Its lifetime is the entire program.
C++ STATIC DATA MEMBERS
• Syntax
className {
static data_type data_member_name;
.....
}
• Static data members are useful for maintaining data shared among all instances of a class.
DEFINING STATIC DATA MEMBER
• the static members are only declared in the class declaration. If we try to access the static data
member without an explicit definition, the compiler will give an error.
• To access the static data member of any class we have to define it first and static data members
are defined outside the class definition.
• The only exception to this are static const data members of integral type which can be
initialized in the class declaration.
DEFINING STATIC DATA MEMBER
• Syntax
datatype class_name::var_name = value...;
For example, in the above program, we have initialized the static data member using the following
statement:
int A::x = 10
The static data members are initialized at compile time so the definition of static members should be
present before the compilation of the program
DEFINING STATIC DATA MEMBER
In C++, static data members belong to the class itself, not to individual objects. This creates a
fundamental difference in initialization compared to normal (non-static) members.
1. Static Data Members Are Shared Across All Objects: Static members are not part of any
individual object’s memory; instead, they exist only once per class, in a separate memory
location. Because of this, C++ requires them to be defined and initialized outside the class.
2. C++ Rules Prevent Direct Initialization in the Class Body:A class is only a blueprint, and
static members do not belong to any single object. Since they live outside any instance, initializing
them inside the class definition would not make sense.
DEFINING STATIC DATA MEMBER
• Example of Incorrect Initialization (Not • Correct Way to Initialize Static Members
Allowed)
class Example {
class Example { public:
static int x = 10; // ❌ Not allowed static int x; };
}; // Definition and Initialization outside the class
int Example::x = 10; // ✅ Allowed (allocated in
global/static memory)
int main() {
std::cout << Example::x; // Output: 10
return 0;}
DEFINING STATIC DATA MEMBER
Exception: Inline Initialization for const static Members
• Starting from C++11, we can initialize const static integral (like int, char, bool) members inside
the class.
class Example {
public:
static const int x = 10; // ✅ Allowed for const static integral types
};
// No need for `Example::x = 10;` outside the class
ACCESSING A STATIC MEMBER
• We can access the static data member without creating the instance of the class. Just remember
that we need to initialize it beforehand. There are 2 ways of accessing static data members:
1. Accessing static data member using Class Name and Scope Resolution Operator
The class name and the scope resolution operator can be used to access the static data member even
when there are no instances/objects of the class present in the scope.
Syntax
Class_Name :: var_name
Example
A::x
ACCESSING A STATIC MEMBER
2. Accessing static data member through Objects
We can also access the static data member using the objects of the class using dot operator.
Syntax
object_name . var_name
Example
obj.x
Note: The access to the static data member can be controlled by the class access modifiers.
C++ STATIC DATA MEMBERS: EXAMPLE
class A { int main(){
public: cout << "Accessing static data member: " << A::x
static int x; << endl;
A() { cout << "A's constructor called " <<
endl; }
return 0;
}; }
int A::x = 2;
CHARACTERISTICS OF STATIC DATA
MEMBERS
• static data members can be private. They follow the same access control rules as regular data
members and can be accessed through public member functions of the class.
• static data members must be defined outside the class definition. However, they can be
initialized inline if they are of integral or enumeration type (C++17 onwards).
• Static data members are class-specific and cannot be inherited. But we can access the static data
member in the derived class directly using variable name
• static member functions can be defined in a class. They can access static data members but
cannot access non-static data members or this pointer.
STATIC MEMBER FUNCTION IN C++
Static Member Function in a class is the function that is declared as static because of which function attains
certain properties as defined below:
• A static member function is independent of any object of the class.
• A static member function can be called even if no objects of the class exist.
• A static member function can also be accessed using the class name through the scope resolution
operator.
• A static member function can access static data members and static member functions inside or
outside of the class.
• Static member functions have a scope inside the class and cannot access the current object pointer.
• You can also use a static member function to determine how many objects of the class have been created.
STATIC MEMBER FUNCTION IN C++
The reason we need Static member function:
• Static members are frequently used to store information that is shared by all objects in a class.
• For instance, you may keep track of the quantity of newly generated objects of a specific class
type using a static data member as a counter. This static data member can be increased each time
an object is generated to keep track of the overall number of objects.
STATIC MEMBER FUNCTION IN C++
class Box { int Box :: breadth = 20;

private: int Box :: height = 30;

static int length; // Driver Code

static int breadth; int main() {

static int height; Box b;

public: cout << "Static member function is called through Object name: \
n" << endl;
static void print() {
b.print();
cout << "The value of the length is: " << length << endl;
cout << "\nStatic member function is called through Class
cout << "The value of the breadth is: " << breadth << endl;
name: \n" << endl;
cout << "The value of the height is: " << height << endl; }};
Box::print();
// initialize the static data members
return 0; }
int Box :: length = 10;
STATIC MEMBER FUNCTION IN C++
Static members belong to the class rather than an individual object. They are shared among all
objects of the class.
Static Data Members
• Declared using static, and memory is allocated only once for the entire class.
• Must be defined outside the class.
Static Member Functions
• Can access only static members.
• Cannot access instance-specific data members.
INLINE FUNCTION
INLINE FUNCTIONS IN C++
• In C++, a function can be specified as inline to reduce the function call overhead.
The whole code of the inline function is inserted or substituted at the point of its
call during the compilation instead of using normal function call mechanism.
• Syntax:
• We just need to add the “inline” keyword before the function prototype:
inline return_type function_name(params)...
INLINE EXAMPLE
inline void displayNum(int num) { // second function call
cout << num << endl; displayNum(8);
}
int main() { // third function call
// first function call displayNum(666);
displayNum(5); return 0;
}
INLINE EXAMPLE
INLINE FUNCTIONS IN C++
Inlining is only a request to the compiler, not a command. The compiler may not
perform inlining in such circumstances as:
1. If a function contains a loop.
2. If a function contains static variables.
3. If a function is recursive.
4. If a function contains a switch statement.
NEED OF INLINE FUNCTIONS
• When a function is called, the CPU stores the return address, copies arguments to the stack, and
transfers control to the function. After execution, the return value is stored, and control is returned
to the caller.
• This overhead can be significant for small, frequently used functions, as their execution time is
less than the time spent on the call and return process.
• This is where the inline functions shine. They remove this overhead by substituting the code of
the function in place of function call.
NEED OF INLINE FUNCTIONS
• One other thing to remember is that it is only useful to make the function inline if the time spent
during a function call is more compared to the function body execution time.
INLINE FUNCTIONS IN CLASS
• All the functions defined inside the class are implicitly inline. Thus, all the restrictions of inline
functions are also applied here. If you need to explicitly declare an inline function in the class,
then just declare the function inside the class and define it outside the class using the inline
keyword.

class A { // Define the function


public: inline int A::square(int x) {
// declare inline return x*x;
inline int square(int x); }
};
O B J E C T A R R AY
O B J E C T A R R AY
• An object array is an array where each element is an instance of a class. Instead of creating
multiple individual objects, we can use an array to handle a collection of objects of the same
class.
• Syntax
ClassName ObjectName[number of objects];
• The Array of Objects stores objects. An array of a class type is also known as an array of objects.
• Example: A school system needs to store information for 50 students. Instead of declaring
50 separate objects, we can use an array of objects.
EXAMPLE
class Student { int main() {
public: Student students[2];
std::string name; students[0].name = "Alice";
int age; students[0].age = 20;
students[1].name = "Bob";
void display() { students[1].age = 22;
std::cout << "Name: " << name << ", Age: " << age
<< std::endl;}
for (int i = 0; i < 2; i++) {
};
students[i].display();}
return 0;}
EXAMPLE
• Storing more than one Employee data. Let’s assume there is an array of objects for storing
employee data emp[50].
EXAMPLE: WITHOUT ARRAY OBJECT
class Employee{ { cout<<"Enter Id : "; cout<<endl;}
int id; cin>>id; int main(){
char name[30]; cout<<"Enter Name : "; Employee emp;
public: cin>>name; emp.getdata();
void getdata(); } emp.putdata();
void putdata(); void Employee::putdata() return 0;}
}; { cout<<id<<" ";
cout<<name<<" ";
void Employee::getdata()
EXAMPLE: WITH ARRAY OBJECT
class Employee{ cout << id << " "; cout << "Employee Data - \n“;
int id; cout << name << " "; for(i = 0; i < n; i++)
char name[30]; cout << endl;} }; emp[i].putdata();}
public:
void getdata(){ int main(){
cout << "Enter Id : "; Employee emp[30];
cin >> id; int n, i;
cout << "Enter Name : "; cout << "Enter No of Employees: ";
cin >> name;} cin >> n;
for(i = 0; i < n; i++)
void putdata(){ emp[i].getdata();
OBJECT ARRAY WITH PARAMETERIZED
CONSTRUCTORS
class Student { }};
public:
std::string name; int main() {
int age; Student students[3] = { Student("Alice", 20),
Student("Bob", 22), Student("Charlie", 19) };
Student(std::string n, int a) {
for (int i = 0; i < 3; i++) {
name = n;
students[i].display();}
age = a;}
void display() { return 0;}

std::cout << "Name: " << name << ", Age: " << age
<< std::endl;
ADVANTAGES OF ARRAY OF OBJECTS
• The array of objects represent storing multiple objects in a single name.
• In an array of objects, the data can be accessed randomly by using the index
number.
• Reduce the time and memory by storing the data in a single variable.
DISADVANTAGES OF ARRAY OF OBJECTS
• The main disadvantage with arrays of objects is that the constructor runs for each
object. If the default constructor doesn’t do the right thing for multiple objects in
the array, we have to specify the constructor arguments for each element at the
time the array is declared, which we wouldn’t have to do if we allocated an array
of object pointers, and allocated objects as needed.

You might also like