0% found this document useful (0 votes)
297 views

Object-Oriented Programming Using C++ - Day2

New and delete operators are used to allocate and free memory at run time. The new operator allocates memory and returns a pointer to the start of it. The delete operator frees memory previously allocated using new.

Uploaded by

api-3728136
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
297 views

Object-Oriented Programming Using C++ - Day2

New and delete operators are used to allocate and free memory at run time. The new operator allocates memory and returns a pointer to the start of it. The delete operator frees memory previously allocated using new.

Uploaded by

api-3728136
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Object-Oriented Programming using C++ - Day2

Recap of Day 1
• Programming Techniques
• Introduction to Object Oriented Concepts
• Basics of C++
• Reference Variables
• Parameter Passing techniques
• Abstract Data types
• Classes and Objects
• Access Specifiers
• Class – Best Practices and Guidelines
• Constructors and Destructors

Copyright © 2006, Infosys 2 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
Session Plan - Day 2
• Dynamic Memory Allocation
• Inline Functions
• Static Members
• Const Members
• Polymorphism
• ‘this’ pointer
• Aggregation
• Cin & Cout

Copyright © 2006, Infosys 3 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
Pointer to objects
class Trainee { int main(int argc,char** argv) {
private: Trainee oT1;
int m_iEmpId;
char m_acName[30]; //Declaring a pointer to an Object
float m_fBasic; Trainee* poT1;
float m_fHRA;
public: //Initializing pointer
void SetData(ID,Name,Basic,Hra){ poT1=&oT1;
………//Code
} //Invoking Methods using pointer
void CalculateSal() { poT1->SetData(102,”Dave”,1200,350);
………//Code poT1->CalcuateSal();
} poT1->CalculateTax();
void CalculateTax(){
………//Code return 0;
} }
}; Copyright © 2006, Infosys ER/CORP/CRS/LA38/003
4
Technologies Ltd Version no: 1.1
Dynamic Memory Allocation – new & delete operators
• The new and delete operators are used to allocate and free memory at run time.
• The new operator allocates memory and returns a pointer to the start of it.
• The delete operator frees memory previously allocated using new.
• The general forms of new and delete are shown here:
p_var = new type;
delete p_var;

• Here, p_var is a pointer variable that receives a pointer to memory that is large
enough to hold an item of type type.

• Trainee *poT1 = new Trainee();


vs Trainee *poT1 = (Trainee *) malloc( sizeof(Trainee) );

• Even though malloc/free allocates and releases the memory respectively,


Constructor/Destructor is not called during dynamic object creation/destruction.

• Hence use new/delete for dynamic memory allocation for objects and
malloc/free for primitive data types.

Copyright © 2006, Infosys 5 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
Dynamic Memory Allocation – Example using new & delete

class Trainee {
private: int main(int argc,char** argv) {
int m_iEmpId; //Declaring a pointer to an Object
char m_acName[30]; Trainee* poT1;
float m_fBasic; //Initializing pointer
float m_fHRA; poT1=new Trainee();
public: //Invoking Methods using pointer
void SetData(ID,Name,Basic,Hra){ poT1->SetData(102,”Dave”,1200,350);
………//Code // Releasing Memory
} delete poT1;
void CalculateSal() {
………//Code poT1=new Trainee(101,”Dave”,1200,350);
} poT1->CalculateSal();
void CalculateTax(){ delete poT1;
………//Code }
}
}; Copyright © 2006, Infosys ER/CORP/CRS/LA38/003
6
Technologies Ltd Version no: 1.1
Memory allocation through new and delete

• The dynamic memory allocation happens on the heap.

• Heap is a memory space which grows or shrinks dynamically.

• Whenever the memory is allocated dynamically for any object, a space is


allocated in the heap. This allocation remains until it is deleted (freed).

• If a program fails to de-allocate memory, that memory cannot be used by other


programs. This is called as “memory leak”.
// Example of Memory leak
int main(int argc,char** argv) {
Trainee* poT1=new Trainee();
poT1->SetData(102,”Dave”,1200,350);
poT1->CalculateSal();
return 0;
}
Copyright © 2006, Infosys 7 ER/CORP/CRS/LA38/003
Technologies Ltd Version no: 1.1
Inline Functions
• Normal function-calls eat up lot of CPU time for its bookkeeping activities
• So, for smaller methods, the C++ compiler automatically replaces the function
calls with the actual code to be executed.
• As a programmer, we can also request the compiler to do so.
• This is done usually for smaller and non-recursive functions.
• Inline is a suggestion given to the compiler. Compiler decides whether to replace
or not.

inline double CalcArea() {


return Length * Breadth;
}

Copyright © 2006, Infosys 8 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
Static Members
Static Data Members
• Data member whose value is shared by all the objects of the class
• Static data is allocated memory only once when the class is loaded.
• Must be defined outside the class
• Also can be initialized during definition, If not initial value will be 0.

Static Member Functions


• Provide a very generic functionality that doesn’t require us to instantiate the
class.
• can be invoked without any objects (ie. using class name)
• can access only other static members (static functions or static variables).

Copyright © 2006, Infosys 9 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
Static Members - Example 0
class Trainee { Trainee::Trainee(int iEmpId)
1
private: m_iTotalTrainees++;
int m_iEmpId; m_iEmpid=iEmpId;
2
static int m_iTotalTrainees; }
public: int Trainee::GetTotalTrainees() {
1
Trainee(int iEmpID); return (m_iTotalTrainees);
static int GetTotalTrainees(); } 0
Trainee::~Trainee() {
~Trainee();
m_iTotalTrainess--;
};
}
Trainee::m_iTotalTrainees=0; // MUST

// Main Program // Main Program continued


Trainee *poT1,*poT2; printf(“%d”,Trainee::GetTotalTrainees());
printf(“%d”,Trainee::GetTotalTrainees()); delete poT1;
poT1= new Trainee(1001); printf(“%d”,Trainee::GetTotalTrainees());
printf(“%d”,Trainee::GetTotalTrainees()); delete poT2;
poT2= new Trainee(1002); printf(“%d”,Trainee::GetTotalTrainees());
Copyright © 2006, Infosys 10 ER/CORP/CRS/LA38/003
Technologies Ltd Version no: 1.1
‘const’ Member Functions
• We can prevent methods from modifying data members
Invalid
• Guarantees that value of data member will not gets modified inside constant methods
• Member functions like getter methods, display methods can be made const

class Trainee { void Trainee::SetEmpId(int iEmpID) {


private: m_iEmpId= iEmpID;
int m_iEmpId; }
float m_fSal; void Trainee::SetSal(float fSal) {
m_fSal=fSal;
public:
}
int GetEmpId() const;
int Trainee::GetEmpId() const{
float GetSal() const;
return(m_iEmpId);
void SetSal(float fSal); }
void SetEmpId(int iEmpId); float Trainee::GetSal() const{
}; m_fSal=m_fSal+1000;
return(m_fSal);
}

Copyright © 2006, Infosys 11 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
Mutable Variables

• are data members which can be modified even by ‘const’ methods


• Sometimes we may need to grant permission for constant methods to modify
selective data members.
class Trainee { void Trainee::SetEmpId(int iEmpID) {
m_iEmpId=iEmpID; Invalid
private:
}
int m_iEmpId; void Trainee::SetSal(float fSal) {
float mutable m_fSal; m_fSal=fSal;
public: }
int GetEmpId() const; int Trainee::GetEmpId() const{
return(m_iEmpId);
float GetSal() const;
}
void SalHike() const; float Trainee::GetSal() const{
void SetSal(float fSal); return(m_fSal);
void SetEmpId(int iEmpID); }
void Trainee::SalHike() const{
};
m_fSal=m_fSal+1000;
m_iEmpId=1001;
}
Copyright © 2006, Infosys 12 ER/CORP/CRS/LA38/003
Technologies Ltd Version no: 1.1
const Objects
• Objects which cannot modify the value of data members
• It can invoke only static & const methods

class Trainee { void Trainee::SetEmpId(int iEmpId) {


private: m_iEmpId=iEmpId;
int m_iEmpId; }
float m_fSal; int Trainee::GetEmpId() const{
return(m_iEmpId);
public:
} Invalid
int GetEmpId() const;
void SetEmpId(int iEmpId);
};
const Trainee oT1;
oT1.SetEmpId(100);
printf(“%d”,oT1.GetEmpId());

Copyright © 2006, Infosys 13 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
Function – Default Arguments
SetData(1001,1200)
• Allows function call without supplying all arguments
• Function assigns the default value to the argument which is notSetData(1001,1000)
supplied during
function invocation
• Should be on the trailing end Invalid
• Should be specified either in the function declaration or in definition
class Trainee { void Trainee::SetData(int iEmpId,
private: float fSal) {
int m_iEmpId; m_iEmpId=iEmpId;
float m_fSal; m_fSal=fSal;
public: }
void SetData(int iEmpId,float fSal=1000); void Trainee::CalculateSal() {
void CalculateSal(); // Code to calculate Sal
} }
Trainee oT1;
oT1.SetData(1001,1200);
oT1.SetData(1001);
oT1.SetData();

Copyright © 2006, Infosys 14 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
Polymorphism
• Is a Greek word, which means one name, multiple forms.
• Is the ability of objects to respond differently to the same message. The kind of
response is dependent on the data types used at a given instance.
• Allows objects having different internal structure to share the same external
interface.

Polymorphism

Compile Time Run Time


Polymorphism Polymorphism

Method
Overloading Templates
Virtual
Functions
Operator
Overloading

Copyright © 2006, Infosys 15 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
Polymorphism - Binding

• Binding refers to the process of linking a procedure call to the code to be


executed in response of the call.
• Are of two types.
– Static binding or Early or Compile time binding and
– Dynamic binding or Late or Runtime binding.
• In Static binding the code associated with a given procedure call is resolved
during compiler time.
• In Dynamic binding the code associated with a given procedure call is resolved
during run-time.

Copyright © 2006, Infosys 16 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
Function Overloading
• In C++, we can have more than one function with the same name.
• The signature of each overloaded function must be unique.
• The signature refers to the number, type and order of the parameters.
• The compiler will determine which version of the function is being invoked by
analyzing the parameters.
int abs(int iNum) {
if(iNum<0) iNum=-iNum;
return (iNum);
}
float abs(float fNum) {
if(fNum<0) fNum=-fNum;
return (iNum);
}

int main(int argc, char * argv[] ) {


int iNum = -10;
float fNum = 2.3f;
printf(“%d”,abs(iNum));
printf(“%f”,abs(fNum));
}
Copyright © 2006, Infosys 17 ER/CORP/CRS/LA38/003
Technologies Ltd Version no: 1.1
Function Overloading and Ambiguity

void fnOne(int iValue1,int iValue2=10) {


printf(“Inside function with two parameters:%d %d“,iValue1,iValue2);
}

void fnOne(int iValue1) {


printf(“Inside function with one parameters: %d“,iValue1);
}
int main(int argc,char** argv) {
fnOne(21);
/*compiler won’t be able to decide which function to be invoked*/

fnOne(10,20); //no ambiguity


}

Copyright © 2006, Infosys 18 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
Constructor overloading

• Similar to functions, methods can also be overloaded


• Class can have more than one methods with same name and different
implementations
• Constructors can also overloaded
• Destructors CANNOT BE overloaded

Copyright © 2006, Infosys 19 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
Method Returning Object - Example
class Circle { Circle::Circle(int iRadius){
private: m_iRadius=iRadius;
int m_iRadius; }
public: float Circle::Area() {
Circle(int iRadius); return(m_iRadius*m_iRadius*3.14);
float Area(); }
Circle ScaleUp(int iTimes); Circle ScaleUp(int iTimes) {
}; Circle oTemp(m_iRadius*iTimes);
return(oTemp);
}

//Usage
Circle oC1(1);
printf(“%f”,oC1.Area());
Circle oC2=oC1.ScaleUp(2);
printf(“%f %f”,oC1.Area(), oC2.Area());

Copyright © 2006, Infosys 20 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
Cascading Method Call - Example
class Circle { Circle::Circle(int iRadius){
Private: m_iRadius=iRadius;
int m_iRadius; }
public: float Circle::Area() {
Circle(int iRadius); return(m_iRadius*m_iRadius*3.14);
float Area(); }
Circle ScaleUp(int iTimes); Circle ScaleUp(int iTimes) {
}; Circle oTemp(m_iRadius*iTimes);
return(oTemp);
}

//Main Program
Circle oC1(1);
printf(“%f”,oC1.Area());
float fArea = oC1.ScaleUp(2).Area();
printf(“%f”,fArea);

Copyright © 2006, Infosys 21 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
‘this’ pointer

• ‘this’ pointer is a pointer that is automatically available in all non-static member


functions of a class.
• Allows objects to access its own address within member functions
• Points to the current object, that is, object that invoked the method.
• When a member function is called, it is automatically passed an implicit
argument that is a pointer to the invoking object
• Since static functions can be called even without objects, ‘this’ pointer cannot
be used with static member functions.

Copyright © 2006, Infosys 22 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
‘this’ pointer - Example
class Circle { void Circle::SetRadius(int iRadius) {
private: this->iRadius=iRadius;
int iRadius; // no m_ }
public: // this is intentional int Circle::GetRadius() {
void SetRadius(int iRadius); return(iRadius); //return(this->iRadius)
void GetRadius() }
float Area(); float Circle::Area() {
}; return(3.14f*iRadius*iRadius);
}

//Main Program

Circle oC1(1);
printf(“%f”,oC1.Area());

Copyright © 2006, Infosys 23 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
Method Returning Object Using ‘this’ pointer - Example
class Circle { Circle::Circle(int iRadius){
private: m_iRadius=iRadius;
int m_iRadius; }
public: float Circle::Area() {
Circle(int iRadius); return(m_iRadius*m_iRadius*3.14)
float Area(); }
Circle ScaleUp(int iTimes); Circle ScaleUp(int iTimes) {
}; this->m_iRadius=m_iRadius*iTimes;
return(*this);
}

//Main Program

Circle oC1(1);
printf(“%f”,oC1.Area());
Circle oC2=oC1.ScaleUp(2);
printf(“%f %f”,oC1.Area(), oC2.Area());
Copyright © 2006, Infosys 24 ER/CORP/CRS/LA38/003
Technologies Ltd Version no: 1.1
Method Returning Reference to an Object - Example
class Circle { Circle::Circle(int iRadius){
private: m_iRadius=iRadius;
int m_iRadius; }
public: Float Circle::Area() {
Circle(int iRadius); return(m_iRadius*m_iRadius*3.14)
float Area(); }
Circle & ScaleUp(int iTimes); Circle& ScaleUp(int iTimes) {
}; this->m_iRadius=m_iRadius*iTimes;
return(*this);
}

//Main Program
Circle oC1(1);
printf(“%f”,oC1.Area());
Circle oC2=oC1.ScaleUp(2);
printf(“%f %f”,oC1.Area(), oC2.Area());

Copyright © 2006, Infosys 25 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
Method Returning pointer to an Object - Example
class Circle { Circle::Circle(int iRadius){
Private: m_iRadius=iRadius;
int m_iRadius; }
public: float Circle::Area() {
Circle(int iRadius); return(m_iRadius*m_iRadius*3.14f);
float Area(); }
Circle* ScaleUp(int iTimes); Circle* ScaleUp(int iTimes) {
}; this->m_iRadius=m_iRadius*iTimes;
return(this);
}

//Main Program
Circle oC1(1);
Circle* poC1;
printf(“%f”,oC1.Area());
poC2=oC1.ScaleUp(2);
printf(“%f %f”,oC1.Area(), poC2->Area());
Copyright © 2006, Infosys 26 ER/CORP/CRS/LA38/003
Technologies Ltd Version no: 1.1
Aggregation

• refers to a relationship where one class contains objects of another class as


it’s data members
• is also called as “Has-A” relationship and also called as “Containership”

Circle Point

- Center: Point -X : Integer


- Radius: Integer -Y : Integer

+SetRadius (Integer): void +SetX (Integer): void


+SetCenter(Point): void +SetY(Integer): void
+GetRadius(): Integer +GetX(): Integer
+GetCenter(): Point +GetY(): Integer

Copyright © 2006, Infosys 27 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
Aggregation – Example (1 of 3)
// Class Point Declaration // Class Point Implementation
Point::Point(int iX,int iY) {
class Point { m_iX=iX;
private: m_iY=iY;
}
int m_iX;
void Point::SetX(int iX) {
int m_iY;
m_iX=iX;
public:
}
Point(int iX, int iY); void Point::SetY(int iY) {
void SetX(int iX); m_iY=iY;
void SetY(int iY); }
int GetX(); int Point::GetX() {
int GetY(); return (m_iX);
}; }
int Point::GetY() {
return(m_iY);
}

Copyright © 2006, Infosys 28 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
Aggregation – Example (2 of 3)
//Class Circle declaration // Class Circle implementation
Circle::Circle(Point oP1,int iRadius) {
class Circle{
m_oCenter=oP1;
private: m_iRadius=iRadius;
Point m_oCenter; }
int m_iRadius; void Circle::SetCenter(Point oP1) {
public: m_oCenter=oP1;
}
Circle(Point oP1,int iRadius);
void Circle::SetRadius(int iRadius) {
void SetCenter(Point oP1); m_iRadius=iRadius;
void SetRadius(int iRadius); }
int GetRadius(); int Circle::GetRadius() {
returrn(m_iRadius);
float Area();
}
Point& GetCenter(); float Circle::Area() {
}; return(3.14*m_iRadius*m_iRadius);
}
Point& GetCenter() {
return(m_oCenter);
}
Copyright © 2006, Infosys 29 ER/CORP/CRS/LA38/003
Technologies Ltd Version no: 1.1
Aggregation – Example (3 of 3)
int main(int argc,char** argv) {
Point oCenter(100,100); // Point object representing (100,100)
Circle oC1(oCenter,10); //Circle Object with center (100,100) and radius 10

oC1.GetCenter().SetX(50);
oC1.GetCenter().SetY(50);
oC1.SetRadius(3);

printf(“\nArea=%d”,oC1.Area());

return 0;
}

Copyright © 2006, Infosys 30 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
Operator Overloading - A feature of C++

• provides the idea of Extensibility.

• That is adding new definitions to the existing operators. In other words, giving
extra work to the operator that already has some work.

• However this is not commonly used and hence is not discussed here

Copyright © 2006, Infosys 31 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
Input/Output Statements – cin and cout
• cin is used for accepting data from the user
• cout is used for displaying information on the monitor
• cin and cout are declared in the header file iostream.h, So, it should be included using
#include<iostream>

• The syntax of cout (statement):

cout << String-Mesg/variable-name1 << String-Mesg/variable-name2 … ;

• Here, << is called insertion operator which inserts output to Output Device (Monitor).

• Typically the data in the output stream may get onto the monitor by default or can be
redirected to files or any other output device.

• Examples:
cout<<“Hello World” ;
cout<<“Infosys Technologies Ltd., \n”;
cout<<“Employee Name : “<< acName << endl;
cout<<“\t\t Employee Number : “ << iEmpID << “\n”;
Copyright © 2006, Infosys 32 ER/CORP/CRS/LA38/003
Technologies Ltd Version no: 1.1
Input/Output Statements – cin and cout
• The syntax of cin (statement):

cin >> variable-name1 >> variable-name2 >> variable-name3 …;

• Here, >> is called extraction operator which extracts input from


keyboard to variable.

• Examples:
cout<< “ Enter your name : “;
cin >> acName ; // reads a string
cout<< “ Enter your Emp_ID and Salary : “;
cin >> iEmpID >> fSalary; // reads an integer and
// a floating point number

Copyright © 2006, Infosys 33 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
Summary
• Dynamic Memory Allocation
• Inline Functions
• Static Members
• Const Members
• Polymorphism
• Function/Method Overloading
• Ambiguity in Function Overloading
• this pointer
• Aggregation
• Cin & Cout

Copyright © 2006, Infosys 34 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1
Thank You!

Copyright © 2006, Infosys 35 ER/CORP/CRS/LA38/003


Technologies Ltd Version no: 1.1

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy