0% found this document useful (0 votes)
19 views7 pages

Storage Classes Arrays Strings Dynamic Memory Management Content - V1.1

C++ - Storage Classes, Arrays, Strings, Dynamic Memory Management and CPPCheck Storage classes like static, extern and register define the scope and lifetime of variables. Const qualifier prevents modification of objects. The string class manages character arrays dynamically. Dynamic memory is allocated using new/new[] and freed using delete/delete[] to handle runtime memory requirements. The CppCheck tool checks C/C++ code for bugs and issues.

Uploaded by

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

Storage Classes Arrays Strings Dynamic Memory Management Content - V1.1

C++ - Storage Classes, Arrays, Strings, Dynamic Memory Management and CPPCheck Storage classes like static, extern and register define the scope and lifetime of variables. Const qualifier prevents modification of objects. The string class manages character arrays dynamically. Dynamic memory is allocated using new/new[] and freed using delete/delete[] to handle runtime memory requirements. The CppCheck tool checks C/C++ code for bugs and issues.

Uploaded by

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

C++ - Storage Classes, Arrays, Strings, Dynamic Memory Management and CPPCheck

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

Static Members (Data and Functions)


class Myclass
{
Static data members are :
public:
initialized at the start of program (before entering main) static int GetValue() {return a;};
private:
static members of a class are common to all objects static int a;//static member
};
exist till the lifetime of the program
int Myclass::a = 10; //static member initi
accessed using :: int main()
{
Static Member Functions are : Myclass obj, obj2;
cout << Myclass::GetValue();
Used to access static data members only cout << obj.Getvalue();
cout << obj2.Getvalue();
}
Video #. Static Member Functions

Applications:
To count instances of a class
log file which is common to all objects of a given class

Const member Functions and Objects

Used to block update of object’s data in the function. Violation will result in compile time error.

Can be called on any type of object (const and non-const objects).


Const objects needs to be initialized at the time of declaration using constructor.

int getValue() const {return value;}

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)

supports functions to perform various operations

Video #. String Functions

length() - return length of string excluding \0


at(<index>) – return character at given index
front() – return first character
back() – return last character
c_str() – return null terminated string as char *
append() – append a string
substr(<start index>, <end index>) - return chars from start upto end index as a string
find(<searchstring>) – return pos of string if found else, return string:npos which is -1
erase(<start index>, <end index>) – delete the characters
replace(<start index>, <end index> , <replace string>)
getline() – store the user input stream of characters
push_back() – input a character at the end
pop_back() - Introduced from C++11(for strings), this function is used to delete the last character from the string

int main()
{
string str1;
char str[100];

cout << "Enter string1: ";


getline(cin, str1);
Know more on strings?
cout << "Enter string2: ";
// will read 100 chars or less untill ‘\n’ , leaving ‘\n’ in buffer
cin.get()
cin.get(str, 100,vs getline()
'\n');

//will read ‘\n’ and return without reading input


cout More on astring
<< "Enter applications
string3: ";
getline(cin, str1);
} String Conversion functions

Pushback Vs append Vs operator

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

Solution is to use dynamic memory allocation

Dynamic Memory Management using new and delete


For growing runtime memory requirements, use new/new[] and delete/delete[] to allocate and
deallocate dynamic memory respectively.
Internally it calls the global new and delete operators (which are static members by default and are
defined in global namespace).
If allocation succeeds, it returns a valid pointer to allocated memory. Else throws bad_alloc exception
and terminates the program.
new and delete on a user defined class object, invokes the constructor and destructor automatically.
To skip call to constructor (i.e like malloc behaviour), use ::operator new().
For customized dynamic allocation/deallocation, overload new and delete operators.
void∗ operator new(std::size_t count); // allocate space for 1 object
void* operator new[]( std::size_t count ); // allocate for an array of objects void operator delete(void∗ p);
int main() void operator delete [] (void *p);
{
char *prefix = new char ('c'); //1 byte initialized with 'c' int main()
char *ptr=new char[40]{ 'c', 'h', 'a', 'r', '_', 'p','\0' }; {
//new char("char_p"); shall throw error as it is incorrect allocation char *prefix = new char ('c');
char *prefixstr = new char [3]; //3 byte allocation delete prefix;
int *val1 = new int; //initalized with default, undefined char *prefixstr = new char [3];
int *val2 = new int(); //initialized with 0 delete [] prefixstr;
int *val
Video #4.= Dynamic
new int(10); Memory
// initialsed Management
with 10 in C++ }
string *str = new string(5,'A'); //initialized with "AAAAA"
Myclass *arrobj = new Myclass[5]; //create an array of objects
}

Dynamic Memory Management – User defined objects

4/7
#define DEFAULT_ARRAY_SIZE 10
int main()
class Myclass
{
{
public:
Myclass *cobj = NULL;

//default constructor //using default constructor


Myclass():data(new int[DEFAULT_ARRAY_SIZE] {1,2,3,5}), cobj = new Myclass;
loc(new char[MAX_LOC_LENGTH]{'B', 'G','L','\0'}) {} Myclass *cobj2 = NULL;
char location[]="CBE";
//parameterised constructor
Myclass(int sz, char *loc):
//using parameterised constructor
data(new int[sz]{99}), loc(new char[strlen(loc) +1]) {}
cobj2 = new Myclass(3, location);

~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

class Myclass void *Myclass::operator new(size_t sz)


{ {
public: cout << "oper new" << endl;
//absence of operator new will call default return (::operator new(sz));
//provided by compiler }
void *operator new(size_t sz); void Myclass::operator delete(void *p)
void operator delete(void *p) {
private: cout << "Destructor" << endl;
int *data; free(p);
}; }

Applications of new/delete overloading


Tracking and profiling of memory, and to detect memory leaks
To create object pools to optimize memory usage

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 ?

CppCheck Tool features and usage

Summary

Use appropriate access specifier for the variables as your requirement


All objects of a class share the static data members.
Use static accessors to access static members.
Use const qualifier to block an update of an object in a function.
Use new/new [] for allocation and delete/delete [] for deallocation of dynamic memory.
For customized dynamic memory handling, overload new and delete operators.
::operator new only allocates memory and hence no call to constructor.

Reference Codes

6/7
Presentation

Assignments

C++ Reference

C++ Libraries

C++ Styleguide

C++ Dynamic Memory Management FAQ

C++ const FAQ

Static member functions

7/7

You might also like