Unit I CPP Notes
Unit I CPP Notes
Unit I Introduction to OOP 7/2/2024 ‹#› Object Oriented Concepts using C++
Emphasis is on doing things (algorithms). Large programs are divided into smaller programs known
as functions. Most of the functions share global data. Data move openly around the system from
function to function. Functions transform data from one form to another. Employs top-down
approach in program design ‹#›
Design methodology for creating a non-rigid application Works on entity called as objects
Decompose problem in to small unit of work which are accessed via Objects. Emphasis is on data
rather than procedure. Data is hidden and cannot be accessed by external function. Objects may
communicate with each other through function. Follows bottom up approach in program design.
Object Oriented Programming 7/2/2024 ‹#› Object Oriented Concepts using C++
Features of OOP Programming language with OOP support has to fulfill these features Abstraction
Encapsulation Inheritance Polymorphism 7/2/2024 ‹#› Object Oriented Concepts using C++
Real life Example Mobile as an object was designed to provide basic functionality as Calling and
Receiving calls Messaging Thousands of new features and models are getting added 7/2/2024 ‹#›
Object Oriented Concepts using C++
Objects Any real world entity which can have some characteristics or which can perform some
work. an instance i.e. - a copy of an entity in programming language. A mobile manufacturing
company, at a time manufactures lacs of pieces of each model which are actually an instance.
objects are differentiated from each other via some identity (e.g. IMEI number) or its characteristics.
Mobile mbl1 ; Mobile mbl2 ; 7/2/2024 ‹#› Object Oriented Concepts using C++
Class 7/2/2024 ‹#› Object Oriented Concepts using C++ class Mobile { private: string IMEICode,
SIMCard, Processor; int InternalMemory; bool IsSingleSIM; public: void GetIMEICode() { cout
"IMEI Code - IEDF34343435235"; } void Dial() { cout "Dial a number"; } void Receive() { cout
"Receive a call"; } void SendMessage(){ cout "Message Sent"; } }
A Class is a plan which describes the object. We call it as a blue print of how the object should be
represented. Mainly a class would consist of a name, attributes and operations. A Mobile can be a
class which has some attributes like Profile Type, IMEI Number, Processor, etc. and operations like
Dial, Receive and SendMessage. ‹#›
Abstraction Abstraction - only show relevant details and rest all hidden its most important pillar in
OOPS as it is providing us the technique to hide irrelevant details from User Dialing a number calls
some method internally which concatenate the numbers and displays it on screen but what is it
doing we don’t know. Clicking on green button actual send signals to calling person’s mobile but we
are unaware of how it is doing. 7/2/2024 ‹#› Object Oriented Concepts using C++ void Dial() {
//Write the logic cout "Dial a number"; }
Encapsulation Encapsulation is defined as the process of enclosing one or more details from
outside world through access right. It specifies how much access should be given. Both Abstraction
and Encapsulation works hand in hand because Abstraction says what details to be made visible
and Encapsulation provides the level of access right to that visible details. i.e. – It implements the
desired level of abstraction. private: string IMEICode = "76567556757656"; 7/2/2024 ‹#› Object
Oriented Concepts using C++
Polymorphism Polymorphism can be defined as the ability of doing the same operation but with
different type of input. More precisely we say it as ‘many forms of single entity’ Static or Compile
time polymorphism Compile time polymorphism the compiler knows which overloaded method it is
going to call. 7/2/2024 ‹#› Object Oriented Concepts using C++ class Samsumg :public Mobile {
public: void GetWIFIConnection() { cout"WIFI connected"; }
//This is one method which shows camera functionality void CameraClick() { cout“Camera clicked";
} //overloaded method which shows camera functionality as well but with panaroma mode
void CameraClick(string CameraMode) { cout"Camera clicked in " + CameraMode + " Mode"; } }
Inheritance Ability to extend the functionality from base entity to new entity belonging to same
group. This will help us to reuse the functionality which is defined before. There are mainly 4 types
of inheritance: Single level inheritance Multi-level inheritance Hierarchical inheritance Hybrid
inheritance Multiple inheritance 7/2/2024 ‹#› Object Oriented Concepts using C++
Inheritance Single level inheritance Single base class and a single derived class i.e. - A base
mobile features are extended by Samsung brand. Multi level inheritance In Multilevel inheritance,
there is more than one single level of derivation. E.g. After base features are extended by Samsung
brand, a new model is launched with latest Android OS 7/2/2024 ‹#› Object Oriented Concepts
using C++
Inheritance Hierarchical inheritance Multiple derived class would be extended from base class It’s
similar to single level inheritance but this time along with Samsung, Nokia is also taking part in
inheritance. Hybrid inheritance Single, Multilevel, and hierarchal inheritance all together construct a
hybrid inheritance. 7/2/2024 ‹#› Object Oriented Concepts using C++
Object based Vs Oriented Language objects-based programming are languages that support
programming with objects Feature that are required for object- based programming are: Data
encapsulation Data hiding and access mechanisms Automatic initialization and clear-up of objects
Operator overloading E.g. Visual Basic Object-oriented programming language incorporates two
additional features, namely, inheritance and dynamic binding Feature that are required for object-
oriented programming are: Data encapsulation Data hiding and access mechanisms Automatic
initialization and clear-up of objects Operator overloading Inheritance dynamic binding 7/2/2024 ‹#›
Object Oriented Concepts using C++
Benefits of OOP We can build the programs from standard working modules that communicate with
one another, rather than having to start writing the code from scratch which leads to saving of
development time and higher productivity, It is very easy to partition the work in a project based on
objects. OOP language allows to break the program into the bit-sized problems that can be solved
easily (one object at a time). The new technology promises greater programmer productivity, better
quality of software and lesser maintenance cost. OOP systems can be easily upgraded from small
to large systems. It is possible to map the objects in problem domain to those in the program. The
principle of data hiding helps the programmer to build secure programs which cannot be invaded by
the code in other parts of the program. By using inheritance, we can eliminate redundant code and
extend the use of existing classes. The data-centered design approach enables us to capture more
details of model in an implementable form. 7/2/2024 Object Oriented Concepts using C++ ‹#›
Application of OOP Real-business system are often complex and contain many objects with
complicated attributes and methods. Some of the areas of application of OOPs are: Real-time
system Simulation and modeling Object-oriented data bases AI and expert systems Neural
networks and parallel programming Decision support and office automation systems CAD/CAM
systems 7/2/2024 ‹#› Object Oriented Concepts using C++
Introduction to C++ ? C++ is a versatile language for handling very large programs including
editors, compilers, databases, communication systems and any complex real-life applications C++
allows create hierarchy related objects to build special object-oriented libraries which can be used
later by many programmers. the C part of C++ gives the language the ability to get close to the
machine-level details. C++ programs are easily maintainable and expandable 7/2/2024 ‹#› Object
Oriented Concepts using C++
Simple C++ Program // Simple C++ program to display "Hello World" // Header file for input output
functions #includeiostream using namespace std; // main function - where the execution of program
begins int main() { // prints hello world cout"Hello World"; return 0; } 7/2/2024 ‹#› Object Oriented
Concepts using C++
It is a common practice to organize a program into three separate files The class declarations are
placed in a header file and the definitions of member functions go into another file. The main
program that uses the class is placed in a third file which “includes” the previous two files as well as
any other file required Structure of C++ Program 7/2/2024 Object Oriented Concepts using C++ ‹#›
C/C++ Compilation and Linking 7/2/2024 ‹#› Object Oriented Concepts using C++ Preprocessor
Linker Compiler Source code file (program.c) Expanded source code (program.i) Object Code
(program.obj) Executable file (program.exe)
‹#› C++ Function Definition C++ function is defined in two steps (preferably but not mandatory) Step
#1 – declare the function signature in either a header file (.h file) or before the main function of the
program Step #2 – Implement the function in either an implementation file (.cpp) or after the main
function 7/2/2024 Object Oriented Concepts using C++
‹#› The Syntactic Structure of a C++ Function A C++ function consists of two parts The function
header, and The function body The function header has the following syntax The function body is
simply a C++ code enclosed between { } return value name (parameter list) 7/2/2024 Object
Oriented Concepts using C++
‹#› Example of User-defined C++ Function double computeTax(double income) { if (income 5000.0)
return 0.0; double taxes = 0.07 * (income-5000.0); return taxes; } 7/2/2024 Object Oriented
Concepts using C++
‹#› double computeTax(double income) { if (income 5000.0) return 0.0; double taxes = 0.07 *
(income-5000.0); return taxes; } Example of User-defined C++ Function Function header 7/2/2024
Object Oriented Concepts using C++
‹#› Example of User-defined C++ Function double computeTax(double income) { if (income 5000.0)
return 0.0; double taxes = 0.07 * (income-5000.0); return taxes; } Function header Function body
7/2/2024 Object Oriented Concepts using C++
Function Signature The function signature is actually similar to the function header except in two
aspects: The parameters’ names may not be specified in the function signature The function
signature must end with a semicolon Example 7/2/2024 Object Oriented Concepts using C++ ‹#›
double computeTaxes(double) ; Unnamed Parameter Semicolon ;
‹#› Why Do We Need Function Signature? For Information Hiding If you want to create your own
library and share it with your customers without letting them know the implementation details, you
should declare all the function signatures in a header (.h) file and distribute the binary code of the
implementation file For Function Abstraction By only sharing the function signatures, we have the
liberty to change the implementation details from time to time to Improve function performance
make the customers focus on the purpose of the function, not its implementation 7/2/2024 Object
Oriented Concepts using C++
‹#› Example #include iostream #include string using namespace std; // Function Signature double
getIncome(string); double computeTaxes(double); void printTaxes(double); void main() { // Get the
income; double income = getIncome("Please enter the employee income: "); // Compute Taxes
double taxes = computeTaxes(income); // Print employee taxes printTaxes(taxes); } double
computeTaxes(double income){ if (income5000) return 0.0; return 0.07*(income-5000.0); } double
getIncome(string prompt){ cout prompt; double income; cin income; return income; } void
printTaxes(double taxes){ cout "The taxes is $" taxes endl; } 7/2/2024 Object Oriented Concepts
using C++
Default Arguments in Function 7/2/2024 ‹#› Object Oriented Concepts using C++ // C++ Program to
demonstrate working of default argument #include iostream using namespace std; void display(char
= '*', int = 1); int main() { cout "No argument passed:\n"; display(); cout "\nFirst argument passed:\n";
display('#'); cout "\nBoth argument passed:\n"; display('$', 5); return 0; } void display(char c, int n) {
for(int i = 1; i = n; ++i) { cout c; } cout endl; }
In C++ programming, you can provide default values for function parameters. The idea behind
default argument is simple. If a function is called by passing argument/s, those arguments are used
by the function.But if the argument/s are not passed while invoking a function then, the default
values are used. Default value/s are passed to argument/s in the function prototype. ‹#›
‹#› Example of Reference Parameters #include iostream.h void fun(int andy) { cout y endl; y=y+5; }
void main() { int x = 4; // Local variable fun(x); cout x endl; } void main() { int x = 4; fun(x); cout x
endl; } 1 7/2/2024 Object Oriented Concepts using C++
‹#› Example of Reference Parameters #include iostream.h void fun(int andy) { cout y endl; y=y+5; }
void main() { int x = 4; // Local variable fun(x); cout x endl; } void main() { int x = 4; fun(x); cout x
endl; } 2 3
‹#› Example of Reference Parameters #include iostream.h void fun(int andy) { cout y endl; y=y+5; }
void main() { int x = 4; // Local variable fun(x); cout x endl; } void main() { int x = 4; fun(x); cout x
endl; } 2 4 9
‹#› Example of Reference Parameters #include iostream.h void fun(int andy) { cout y endl; y=y+5; }
void main() { int x = 4; // Local variable fun(x); cout x endl; } void main() { int x = 4; fun(x); cout x
endl; } 2 5
Classes and Objects 7/2/2024 ‹#› Object Oriented Concepts using C++
Class A way to bind data and associated function together An expanded concept of a data
structure, instead of holding only data, it can hold both data and function. The data is to be hidden
from external use. 7/2/2024 ‹#› Object Oriented Concepts using C++
Class class class_name { private: variable declaration; public: function declaration; …. } ; body
member function data member access specifiers keyword 7/2/2024 ‹#› Object Oriented Concepts
using C++
Access Specifiers public private Less Restrictive More Restrictive protected Private Area Data
Functions Data Functions Class * By default all items defined in the class are private 7/2/2024 ‹#›
Object Oriented Concepts using C++
Access Specifiers Employee public: string name; protected: string designation; private: int Age;
SalariedEmployee Department Manager CommissionEmployee 7/2/2024 ‹#› Object Oriented
Concepts using C++
Access Specifiers class Person { public: //access control string firstName; //these data members
string lastName; //can be accessed int dateOfBirth; //from anywhere private: string address; // can
be accessed inside the class long int insuranceNumber; //and by friend classes/functions protected:
string phoneNumber; // can be accessed inside this class, int salary; // by friend functions/classes
and derived classes }; 7/2/2024 ‹#› Object Oriented Concepts using C++
Objects A class provides the blueprints for objects, so basically an object is created from a class.
Objects of a class are declared with exactly the same sort of declaration as variables of basic types
7/2/2024 ‹#› Object Oriented Concepts using C++ #include iostream using namespace std; class
Box { public: double length; // Length of a box double breadth; // Breadth of a box double height; //
Height of a box }; int main() { Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of
type Box double volume = 0.0; // Store the volume of a box here }
Objects The objects of class will have their own copy of data members. The public data members of
objects of a class can be accessed using the direct member access operator (.) 7/2/2024 ‹#› Object
Oriented Concepts using C++ int main() { Box Box1; // Declare Box1 of type Box Box Box2; //
Declare Box2 of type Box double volume = 0.0; // Store the volume of a box here // box 1
specification Box1.height = 5.0; Box1.length = 6.0; Box1.breadth = 7.0; // box 2 specification
Box2.height = 10.0; Box2.length = 12.0; Box2.breadth = 13.0; // volume of box 1 volume =
Box1.height * Box1.length * Box1.breadth; cout "Volume of Box1 : " volume endl; // volume of box 2
volume = Box2.height * Box2.length * Box2.breadth; cout "Volume of Box2 : " volume endl; return 0;
}
Array of Objects 7/2/2024 Object Oriented Concepts using C++ ‹#› #include iostream #include
string using namespace std; class Student { string name; int marks; public: void setName() {
cinname; } void setMarks() { cin marks; } void displayInfo() { cout "Name : " name endl; cout "Marks
: " marks endl; } }; int main() { Student st[5]; for( int i=0; i5; i++ ) { cout "Student " i + 1 endl; cout
"Enter name" endl; st[i].setName(); cout "Enter marks" endl; st[i].setMarks(); } for( int i=0; i5; i++ ) {
cout "Student " i + 1 endl; st[i].displayInfo(); } return 0; }
Inline functions On function call instruction, CPU stores the memory address of instruction following
the function call CPU then transfers the control to callee function CPU executes callee function,
stores function return value at predefined memory location/register and returns control back to
caller It becomes an overhead if execution time of function is less than switching time for caller
function 7/2/2024 ‹#› Object Oriented Concepts using C++
Inline functions save regs pass args call AddNumbers restore regs z = x – y; 7/2/2024 ‹#› Object
Oriented Concepts using C++
Inline Functions Inline functions reduce the call overhead. Inline functions gets expanded when
called i.e. when inline function is called, entire code of inline function is inserted/substituted at point
of inline function call The substitution is performed by compiler at compile time By default compiler
treats class methods defined under class as inline functions inline return-type
function-name(parameters) { // function code } 7/2/2024 ‹#› Object Oriented Concepts using C++
Static Data Members Dat class Employee { static int EmployeeId; public: int getEmpId (void) {
return ++EmployeeId; } void addEmployee(str); }; void Employee::addEmployee(str name) { newId
= getEmpId(); cout “Added New Empl ” name “ with Id: “ newId endl; …. } int Employee::EmployeeId
int main() { Employee Emp_A, Emp_B; Emp_A.addEmployee(“Amit”);
Emp_B.addEmployee(“Bijoy”); } 0 1 2 EmployeeId=1 EmployeeId=2 7/2/2024 ‹#› Object Oriented
Concepts using C++ # a.out Added New Empl Amit with Id: 1 Added New Empl Bijoy with Id: 2
a members of the class which are shared by all objects are known as static data members. Only
one copy of static variable is maintained by the class and it is common for all objects. Static
members are declared inside the class and defined outside the class. It is initialized to zero when
the first object of its class is created. You cannot initialize a static member variable inside the class
declareation. It is visible only within the class but its lifetime is the entire program. Static members
are generally used to maintain values common to the entire class. ‹#›
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. You can use a static member function to
determine how many objects of the class have been created. 7/2/2024 Object Oriented Concepts
using C++ ‹#›
Static Member Function in C++ 7/2/2024 Object Oriented Concepts using C++ ‹#›
Constructors A constructor is a special member function that is a member of a class and has same
name as that of class. It is used to initialize the object of the class type with a legal initial value. It is
called constructor because it constructs the values of data members of the class. Class A { int a;
float b; char ch; String str; boolean bl; A() { a=10; b=20.0; ch=‘m’; str=“java” bl=true } } 7/2/2024 ‹#›
Object Oriented Concepts using C++
Constructor - Declaration For the T class: T(args); // inside class definition or T::T(args); // outside
class definition class X { int i ; public: int j,k ; X() { i = j = k =0; } }; X::X() { i = j = k =0; } Inside class
Outside class 7/2/2024 ‹#› Object Oriented Concepts using C++
Constructor - Properties Automatically called when an object is created We can define our own
constructors They can not be inherited. These cannot be static. Overloading of constructors is
possible Constructors can have default argument as other C++ functions. If you do not specify a
constructor, the compiler generates a default constructor for you (expects no parameters and has
an empty body). Default and copy constructor are generated by the compiler whenever required.
class X { int i ; public: int j,k ; X() { i = j = k =0; } }; Under public section Does not return anything. Not
even void Name same as Class name 7/2/2024 ‹#› Object Oriented Concepts using C++
Types of Constructors There are several forms in which a constructor can take its shape, namely
7/2/2024 ‹#› Object Oriented Concepts using C++
Default Constructor This constructor has no argument in it Compiler creates one, if not explicitly
defined Default Constructor is also called as no argument constructor class rectangle{ private: float
height; float width; public: rectangle(){ cout “creating rectangle object”; } }; int main() { rectangle rect;
} # a.out creating rectangle object 7/2/2024 ‹#› Object Oriented Concepts using C++
Parameterized Constructors A parameterized constructor is just one that has parameters specified
in it. We can pass the arguments to constructor function when object is created. A constructor that
can take arguments are called parameterized constructors class rectangle{ private: float height;
float width; public: rectangle(float h, float w){ height=h; width=w; } }; int main() { rectangle book(10.0,
20.0); //implicit call rectangle box = rectangle(20.0,30.0) //explicit call rectangle eraser=
rectangle(25.0, 35.0) } 7/2/2024 ‹#› Object Oriented Concepts using C++
Example of default and default parameterized constructor 7/2/2024 Object Oriented Concepts using
C++ ‹#› class rectangle{ private: float height; float width; public: rectangle(float h, float w);
rectangle(){ height=width=1.0; } rectangle(float h, float w=5.0){ height = h; width = w; } }; void main()
{ rectangle book(); //implicit call of default constructor rectangle box(20.0); //implicit call of default
parametrized constructor rectangle eraser(10.0, 20.0); // explicit call of default parametrized
constructor rectangle sharpener = rectangle(10); rectangle geometry_box = rectangle(50.0,70.0);
rectangle paper = rectangle (3.0, 6.0); rectangle calculator = rectangle (15.0, 25.0) //explicit call for
existing object }
Copy Constructor Copy constructor is used to declare and initialize an object from another object If
you have not defined a copy constructor, the complier automatically creates it and it is public Copy
constructor always takes argument as a reference object. The process of initializing through a copy
constructor is known as copy initialization. int main() { rectangle book_1(10.0, 20.0); rectangle
book_2(book_1); } This would define the book_2 object and at the same time initialize it to the value
of book_1. i.e. height and width of book_2 object would be 10 and 20 respectively 7/2/2024 ‹#›
Object Oriented Concepts using C++ class rectangle{ private: float height; float width; public:
rectangle(float h, float w); rectangle(float h, float w){ height=h; width=w; } rectangle(rectangle andp){
height = p.height; width = p.width; } };
Constructor Overloading You can have more than one constructor in a class, as long as each has a
different list of arguments 7/2/2024 Object Oriented Concepts using C++ ‹#› class rectangle{
private: float height; float width; public: rectangle(){ height=width=10.0; } rectangle(float h, float w){
height=h; width=w; } };
Destructors A destructor is used to destroy the objects that have been created by a constructor.
Like constructor, the destructor is a member function whose name is the same as the class name
but is preceded by a tilde. ~T(); It is a good practice to declare destructors in a program since it
releases memory space for further use. 7/2/2024 Object Oriented Concepts using C++ ‹#›
Destructors It is a special member function of a class, which is used to destroy the memory of
object Its name is same as class name but tilde sign preceding destructor It must be declared in
public section It does not return any value; not even void It can be defined inline/offline Does not
need to call because it gets call automatically whenever object is destroyed from its scope It can be
called explicitly also using delete operator It does not take parameters Destructor cannot be
overloaded nor inherited. 7/2/2024 Object Oriented Concepts using C++ ‹#›
Destructors 7/2/2024 Object Oriented Concepts using C++ ‹#› int count=0; class rectangle { public:
rectangle(){ count++; cout"\n Created ObjectId:"count; } ~rectangle() { cout"\n Destroyed
ObjectId:"count; count--; } }; int main() { cout"\n enter main"; rectangle a1,a2,a3,a4; { cout"\nEnter
block1"; rectangle a5; } { cout"\nEnter block2"; rectangle A6; } cout"\nRe-enter main"; return 0; }
#a.out enter main Created ObjectId:1 Created ObjectId:2 Created ObjectId:3 Created ObjectId:4
Enter block1 Created ObjectId:5 Destroyed ObjectId:5 Enter block2 Created ObjectId:5 Destroyed
ObjectId:5 Re-enter main Destroyed ObjectId:4 Destroyed ObjectId:3 Destroyed ObjectId:2
Destroyed ObjectId:1
Dynamic memory allocation Dynamic memory allocation in C/C++ refers to performing memory
allocation at run time as per the program requirement Dynamically allocated memory is allocated on
Heap and non-static and local variables get memory allocated on Stack Memory in C++ program is
divided into two parts − The stack − All variables declared inside the function will take up memory
from the stack. The heap − This is unused memory of the program and can be used to allocate the
memory dynamically when program runs. 7/2/2024 Object Oriented Concepts using C++ ‹#›
Applications of Dynamic memory allocation To allocate memory of variable size which is not
possible with compiler allocated memory The most important use is flexibility provided to
programmers. We are free to allocate and deallocate memory whenever we need and whenever we
don’t need anymore. There are many cases where this flexibility helps. Examples of such cases are
Linked List, Tree, etc 7/2/2024 Object Oriented Concepts using C++ ‹#›
new and delete Operators The new operator denotes a request for memory allocation on the Heap
7/2/2024 Object Oriented Concepts using C++ ‹#› pointer-variable = new data-type; // Pointer
initialized with NULL // Then request memory for the variable int *p = NULL; p = new int; OR //
Combine declaration of pointer // and their assignment int *p = new int; Initialize memory:
pointer-variable = new data-type(value); Example: int *p = new int(25); float *q = new float(75.25);
Pointers and Dynamic Memory Here are the steps: int * myIntPtr; // create an integer pointer
variable myIntPtr = new int; // create a dynamic variable of the size integer new returns a pointer (or
memory address) to the location where the data is to be stored. 7/2/2024 Object Oriented Concepts
using C++ ‹#›
Pointers and Dynamic Memory Free Store (heap) myIntPtr int * myIntPtr myIntPtr = new int;
7/2/2024 Object Oriented Concepts using C++ ‹#›
Pointers and Dynamic Memory Free Store (heap) myIntPtr int * myIntPtr myIntPtr = new int;
*myIntPtr = 123; 1 2 3 Use pointer variable 7/2/2024 Object Oriented Concepts using C++ ‹#›
Pointers and Dynamic Memory We can also allocate entire arrays with the new operator. These are
called dynamic arrays. This allows a program to ask for just the amount of memory space it needs
at run time. 7/2/2024 Object Oriented Concepts using C++ ‹#›
Pointers and Dynamic Memory Free Store (heap) myIntPtr int * myIntPtr; myIntPtr = new int[4];
Notice that the pointer symbol is understood, no * is used to reference the array element. 3 2 5
myIntPtr[1] = 325; 0 2 1 3 7/2/2024 Object Oriented Concepts using C++ ‹#›
Pointers and Dynamic Memory The new operator gets memory from the free store (heap). When
you are done using a memory location, it is your responsibility to return the space to the free store.
This is done with the delete operator. delete myIntPtr; // Deletes the memory pointed delete [ ]
arrayPtr; // to but not the pointer variable 7/2/2024 Object Oriented Concepts using C++ ‹#›
Pointers and Dynamic Memory Dynamic memory allocation provides a more flexible solution when
memory requirements vary greatly. The memory pool for dynamic memory allocation is larger than
that set aside for static memory allocation. Dynamic memory can be returned to the free store and
allocated for storing other data at later points in a program. (reused) 7/2/2024 Object Oriented
Concepts using C++ ‹#›
Example of Dynamic Arrays 7/2/2024 Object Oriented Concepts using C++ ‹#› #include iostream
using namespace std; class Box { public: Box() { cout "Constructor called!" endl; } ~Box() { cout
"Destructor called!" endl; } }; int main() { Box* myBoxArray = new Box[4]; delete [] myBoxArray; //
Delete array return 0; } } Output Constructor called! Constructor called! Constructor called!
Constructor called! Destructor called! Destructor called! Destructor called! Destructor called!
Friend Functions/Classes friends allow functions/classes access to private data of other classes.
Friend functions A 'friend' function has access to all private and protected members (variables and
functions) of the class for which it is a 'friend'. friend function is not the actual member of the class.
To declare a 'friend' function, include its prototype within the class, preceding it with the C++
keyword 'friend'. ‹#› 7/2/2024 Object Oriented Concepts using C++
Example 7/2/2024 Object Oriented Concepts using C++ ‹#› class Boss { public: Boss(); void
giveRaise(double amount); private: Employee e; }; Boss::Boss() {} void Boss::giveRaise(double
amount) { e.salary = e.salary + amount; cout e.salary endl; } class Employee { private: string name;
double salary; public: Employee(); Employee(string n, double s); string getName(); double
getSalary(); }; Employee::Employee() : name(""), salary(0) {} Employee::Employee(string n, double
s): name(n), salary(s) {} string Employee::getName() { return name; } double Employee::getSalary()
{ return salary; } class Employee { private: string name; double salary; friend void
raiseSalary(double a, Employee ande); public: Employee(); Employee(string n, double s); string
getName(); double getSalary(); }; Employee::Employee() : name(""), salary(0) {}
Employee::Employee(string n, double s): name(n), salary(s) {} string Employee::getName() { return
name; } double Employee::getSalary() { return salary; } void raiseSalary(double a, Employee ande)
{ e.salary += a;// Normally not allowed to access e.salary } class Boss { public: Boss(); void
giveRaise(double amount); private: Employee e; }; Boss::Boss() {} void Boss::giveRaise(double
amount) { raiseSalary(amount,e); cout e.getSalary() endl; }