Storage Classes Arrays Strings Dynamic Memory Management Content - V1.1
Storage Classes Arrays Strings Dynamic Memory Management Content - V1.1
Storage class
storage
class
Presentation
Static Members Static and
Const
Members
Assignments
Const Members
C++ Storage
class, static,
const members, References
String class string class, Codes
dynamic
memory
management
Dynamic Memory
Management
CppCheck
Tool String
Dynamic class
CppCheck tool Memory
Management
1/7
Storage Class
Define the scope or visibility and the lifetime of the variable or function within a program
More on auto, static, register, extern, mutable
Const qualifier
volatile
Applications:
To count instances of a class
log file which is common to all objects of a given class
Used to block update of object’s data in the function. Violation will result in compile time error.
String class
2/7
Part of C++ library, internally uses char array and string class manages memory internally
string length is changed at runtime (user need not bother about memory allocation/resizing)
int main()
{
string str1;
char str[100];
Problem
How do I decide on memory requirement in the following cases ?
1. Memory depends on the user input at runtime
2. You need to allocate memory for a large object to be returned by a function
3/7
3. You need to build data structure without enforcing limit on data capacity
4. Read and store the file contents in memory, but file name is to be read from user
4/7
#define DEFAULT_ARRAY_SIZE 10
int main()
class Myclass
{
{
public:
Myclass *cobj = NULL;
~Myclass()
{ delete cobj;
if (data) { delete [] data; data = NULL } delete cobj2;
if (loc) { delete [] loc; loc = NULL; }
}
private:
return 0;
int *data;
}
char *loc;
……..
};
How to manage dynamic memory for class objects using operator new and delete ?
};
Override operator new and operator delete
5/7
New Exception Handling
On new failure std ::bad_alloc() exception is thrown, if unhandled terminâtes the program and exit.
class Myclass;
int main()
{
Myclass *pobj = NULL;
try
{
pobj = new Myclass (10);
}
// will reach here if new fails
catch (bad_alloc xa)
{
cout << "Allocation error.\n";
return 1;
}
return 0;
}
Know more ?
How to simulate bad_alloc and handle the exception?
Can you initialize char* at the time of declaration using new operator?
Difference between delete and delete[]
What is the difference between new/delete and malloc/free?
When do you overload operator new?
What is placement new and operator new ?
Summary
Reference Codes
6/7
Presentation
Assignments
C++ Reference
C++ Libraries
C++ Styleguide
7/7