CSE109 Week11
CSE109 Week11
C++
Lecture: 23-25
Reference Book:
Chapter/Section: -
2
History of C++
⚫ C++ was developed from C
⚫ Written by Dr. Bjarne Stroustrup from Bell Labs in 1979
⚫ “C and classes” and then named C++
⚫ Standardized by ISO in 1998.
⮚ C++98, C++03, C++11 and C++14
Image ref:
https://dotnettrickscloud.blob.core.windows.net/img/cpp/cpp-bac1.pn
g
3
Features of C++
⚫ C++ is OOP and procedural
⚫ Both safer and not safer
⚫ Still has prim. array, but also has safer/slower
array-like objects
⚫ Somewhat stricter typing than in C
⚫ Has namespaces to prevent naming collisions
⚫ Supports function overloading
⚫ Supports operator overloading
⚫ Supports default function parameter values
⚫ Has multiple inheritance
⚫ Has templates
⚫ Many other changes …
4
Input Output in C++
#include<iostream> Will show error if these
using namespace std; two lines are omitted
int main(){
int i;
float j;
Input
char c; Input
1 2.345 A
cin >> i >> j >> c; Output
Output
cout << i <<" "<<j<<" "<<c <<“\n"; 1 2.345 A
return 0;
}
Input Output Formatting in C++
• Formatting is done through #include<iostream>
manipulators. #include<iomanip>
using namespace std;
• Manipulators special
variables or objects that are int main(){
double j=10.2324786,k=345.34375253;
placed on the output cout<<"j="<<j<<endl;
stream. cout<<"k="<<k<<endl;
Default: Max 6-
digits; value
• Most of the standard rounded
cout<<fixed<<setprecision(5);
manipulators are found in cout<<"j="<<j<<endl;
<iostream> cout<<"k="<<k<<endl;
Output
• Manipulator that take
cout<<scientific;
arguments are defined in cout<<"j="<<j<<endl;
<iomanip> cout<<"k="<<k<<endl;
• Some manipulators are return 0;
• endl, setw(size), }
setprecision(size) etc.
• For detail see this link
What is Object Oriented Programming (OOP)
Ref: https://www.slideshare.net/bgjeecourse/objectoriented-concepts-5576132
Principles of OOP
⚫ Encapsulation
⚫ Polymorphism
⚫ Inheritance
Why OOP
⚫ Better suited for team development
⚫ Facilitates utilizing and creating reusable software
components
⚫ Easier GUI programming
⚫ Easier software maintenance
⚫ All modern languages are object-oriented: Java, C#, PHP,
Perl, C++, …
Ref: https://www.slideshare.net/bgjeecourse/objectoriented-concepts-5576132
What are objects
⚫ Software objects model real-world objects or abstract
concepts e.g., dog, bicycle, queue, account
⚫ Real-world objects have states and behaviors
⚫ Dogs’ states: name, color breed, hungry
⚫ Behaviors: barking, fetching, sleeping
⚫ How do software objects implement real-world objects?
⚫ Use variables/data to implement states
⚫ Use methods/functions to implement behaviors
⚫ An object is a software bundle of variables and related
methods
Ref: https://www.slideshare.net/bgjeecourse/objectoriented-concepts-5576132
Classes and Objects
● Each object belongs to a class • Creating an object from a class
is called instantiation
● A class defines
• An object is a concrete instance
● Set of attributes of a particular class
- also called state
• Objects have states
- represented by variables • Set of values associated to their
● Behavior attributes
- represented by methods • Example:
• Class : Account
• Objects: Alice’s account, Bob’s
account
Ref: https://www.slideshare.net/bgjeecourse/objectoriented-concepts-5576132
Class and Object Declaration
class Class-Name{
//Private functions and
variables
public:
//public functions and
variables
} object-list;
● Declaration similar to structure
● class - keyword
● object-list is optional
● Member: functions and variables declared
inside a class
● By default members are private
● Can not be accessed from outside
Example: Class and Object Declaration
#include<iostream>
using namespace std; Class definition;
class Account{ occupies no physical
int accNo; memory
double balance;
public:
void setVals(int a, double b){
accNo=a;
balance=b;
}
void print(){
cout<<"Acc No: "<<accNo<<", Balance: "<<balance<<"\n";
}
};
Access from
clients outside
the class
Accessing Private Members
#include<iostream>
using namespace std;
class Account{
int accNo;
double balance;
public:
void setVals(int a, double b){
accNo=a;
balance=b;
}
void print(){
cout<<"Acc No: "<<accNo<<", Balance: "<<balance<<"\n";
}
};
int main(){
Account a1, a2;
a1.accNo=1;
a1.balance=1000;
return 0;
}
Accessing Public Members
#include<iostream>
using namespace std;
class Account{
int accNo;
double balance;
public:
void setVals(int a, double b){
accNo=a;
balance=b;
}
void print(){
cout<<"Acc No: "<<accNo<<", Balance: "<<balance<<"\n";
}
};
int main(){
Account a1, a2;
a1.setVals(1,1000);
a2.setVals(2,2000); Output
a1.print();
a2.print();
return 0;
}
Setter and Getter Functions
• Setters and Getters are #include<iostream>
using namespace std;
special methods that are class Account{
used to protect data int accNo;
double balance;
• Setters are used to set values public:
to private properties of a //setter functions
void setAccount(int a)
class { accNo=a; }
• Also known as mutators void setBalance(double b)
{ balance=b; }
• Getters are used to read //getter functions
int getAccNo(){ return accNo; }
values of private properties double getBalance(){ return
of a class balance;
int }
main(){
}; Account a;
• Also known as mutators
a.setAccount(1);
• Setters and Getters allow to a.setBalance(1000);
control how important cout<<"Acc No: "<<a.getAccNo()
<<"\n";;
variables are updated and cout<<Balance:
accessed "<<a.getBalance()<<"\n";
return 0;
}
Constructor
Won’t be covered
• A constructor is a special in this term!
member function
• Has the same name as the
class name
• Has no return type
• Invoked implicitly when
instance/object is created
• Can be used for initialization
• Can be overloaded
• Are called in the order of
creation
• Address cannot be taken
Image ref: https://media.geeksforgeeks.org/wp-content/cdn-uploads/20191128195435/CPP-Constructors.png
Example: Constructor
#include<iostream>
using namespace std;
class Account{
int accNo;
double balance;
public:
Account(){
cout<<"In default constructor.\n";
accNo=-1; balance=0; Default Constructor
}
Account(int a, int b){
cout<<"In parameterized constructor.\n";
accNo=a; balance=b; Parameterized Constructor
}
};
Output
a1.Account()
int main(){
Account a1, a2(2,2000);
a2.Account(2,2000)
return 0;
}
Default constructor
● The default constructor is one that can be called without explicit
arguments
● Called when no arguments are provided
●Account acc;
● C++ creates a default constructor if no other regular constructors
are declared
● However, if user defines any constructor other than the default
constructor, the compiler will generate an error if the default
constructor is invoked
Example: Default constructor
#include<iostream>
using namespace std;
class Account{
int accNo;
double balance;
public:
void setVals(int a, double b){
accNo=a;
balance=b;
}
void print(){
cout<<"Acc No: "<<accNo<<", Balance: "<<balance<<"\n";
} As there is no constructor defined
in the class, the compiler will
}; automatically create a default
int main(){ constructor that will be invoked
Account a1;
a1.setVals(1,100); Output
a1.print();
return 0;
}
Example: Default constructor(2)
#include<iostream>
using namespace std;
class Account{
int accNo;
double balance;
public:
Account(int a, double b){
accNo=a; balance=b;
Parameterized
cout<<"In constructor of "<<accNo<<".\n";
} Constructor
};
int main(){
Account a1(1,1000), a2; This will generate a compile error
return 0; as the user has defined a
} parameterized constructor but no
default constructor
Destructor
⚫ Complement of a constructor
⚫ Called automatically when the object is destroyed
⚫ Local object destroyed when goes out of scope
⚫ Global object destroyed when program ends
⚫ Object destroyed using delete operator
⚫ Function name is the name of the class preceded by ~
⚫ Can not take parameters
⚫ Does not declare a return type
⚫ Cannot be overloaded
⚫ Are called in the reverse order of creation
⚫ Address cannot be taken
Example: Destructor
#include<iostream>
using namespace std;
class Account{
int accNo;
double balance;
public:
Account(int a, int b){
accNo=a;
balance=b;
cout<<"In constructor of "<<accNo<<".\n";
}
~Account(){
cout<<"In destructor of "<<accNo<<".\n"; Destructor
}
void print(){
cout<<"Acc No: "<<accNo<<", Balance: "<<balance<<"\n";
Output
}
cco u n t( 1,1000)
}; a1.A )
2. A cco unt(2,2000
int main(){ a
Account a1(1,1000), a2(2,2000);
a1.print(); a2.~Acco
unt()
a2.print();
return 0; Destructors are called in the a1.~Acco
unt()
} reverse order of constructors
Scope Resolution Operator ::
⚫ Scope means “Where something is visible”
⚫ Names can have global scope or be within the scope of a
class
⚫ It is the highest precedence operator in the language
⚫ It comes in two forms:
⚫ :: id // unary operator - refer to global scope
⚫ Account::id // binary operator - refer to class scope
⚫ It can be viewed as a path to the identifier.
⚫ It is the way of specifying what class is associated with
the member function
⚫ Can be used to put class declaration and function
definition in separate files
Classes & Scope Resolution
class Account{ Account::Account(){accNo=-1; balance=0;}
int accNo; Account::Account(int a, double b){
double balance; accNo=a; balance=b;
public: }
//Constructor functions Account::~Account(){cout<<"In the destructor.\
Account(); n";}
Account(int a, double b);
void Account::setAccount(int a){accNo=a;}
//Destructor function void Account::setBalance(double b)
~Account(); { balance=b;}
int main(){
Account a1(1,1000),a2;
cout<<"Before: "; Output
a2.print();
a2=a1;
cout<<"After: ";
a2.print();
return 0;
}
Example: Object Assignment(2)
class Account{ class Employee{
int accNo; int empId;
double balance; double salary;
public: public:
Account(){accNo=-1; balance=-1;} Employee(){empId=-1; salary=-1;}
Account(int a, double b){ Employee(int a, double b){
accNo=a; balance=b; empId=a; salary=b;
} }
void print(){ void print(){
cout<<"Acc No: "<<accNo<<", "; cout<<"Employee Id: "<<empId<<",
cout<<"Balance: "<<balance<<"\ ";
n"; cout<<"Salary: "<<salary<<"\n";
} }
}; };
int main(){
Account a(1,1000);
Employee b(1,1000);
int main(){
3 ways of 7
1 Account a1[3];
for(int i=0;i<3;i++) a1[i].print();
2
initializing an
Account
3
array of objects 8
a2[3]={Account(1,100),Account(2,200),Account(3,300)};
4
for(int i=0;i<3;i++) a2[i].print();
5
Account a3[3]={{10,1000},{20,2000},{30,3000}};
6
for(int i=0;i<3;i++) a3[i].print(); 9
return 0;
}
Object as parameter
⚫ Parameter object is passed by value
⚫ Bitwise copy of the argument made
⚫ When copy of an object made constructor is not called (like
assignment)
⚫ When the function terminates the copy is destroyed
⚫ When the copy is destroyed the destructor is called
⚫ Changes to the object inside function do not affect the object
⚫ Address of the object can be passed
Returning Object
⚫ Can be returned using normal return statement
⚫ When an object is returned from a function a temporary
object is created automatically which holds the return value
⚫ After the value has been returned the object is destroyed
⚫ Careful if the object contains destructor function which frees
memory
Example: Passing and Returning Objects
class Account{ int main(){
int accNo; Account a1(1,500), a2(2,1000);
double balance; a1.print();
public: a2.print();
Account(){
cout<<"In the default constructor.\n"; a1.transferFrom(a2,500);
accNo=-1; balance=0;
} a1.print();
Account(int a, double b){ a2.print();
cout<<"In the parameterized constructor of "<<a<<"\n"; return 0;
accNo=a; balance=b; }
}
~Account(){
cout<<"In the destructor of "<<accNo<<"\n";
}
void transferFrom(Account a, double b){ Output
balance=balance+b;
a.balance=a.balance-b;
Object as a
} parameter
void print(){
cout<<"Acc No: "<<accNo<<", Balance: "<<balance<<"\n";
}
};
Balance not
updated!!
Example: Passing and Returning Objects(2)
class Account{ int main(){
int accNo; Account a1(1,500), a2(2,1000);
double balance; a1.print();
public: a2.print();
Account(){
cout<<"In the default constructor.\n"; a2=a1.transferFrom(a2,500);
accNo=-1; balance=0;
} a1.print();
Account(int a, double b){ a2.print();
cout<<"In the parameterized constructor of "<<a<<"\n"; return 0;
accNo=a; balance=b; }
}
~Account(){
cout<<"In the destructor of "<<accNo<<"\n";
}
Account transferFrom(Account a, double b){
balance=balance+b;
a.balance=a.balance-b;
Object a can directly access object b’s Output
private data, as they are of to the same
return a;
class
}
void print(){
Object as a return value
cout<<"Acc No: "<<accNo<<", Balance: "<<balance<<"\n";
}
};
Balance
updated!!
Nesting Objects: Object member of another object
#include<iostream> class Account{
#include<iomanip> int accNo;
using namespace std; double balance;
class Date {
Date openDate;//Date object memeber of Account
int day, mon, year;
public: public:
date(int d, int m, int y){ void setAccount(int a){accNo=a;}
day = d; mon = m; year = y; void setBalance(double b){balance=b;}
} void setOpenDate(int d, int m, int y){
void setDay(int d) {day=d;} //The below statement will generate error
void setMonth(int m) {mon=m;} //openDate.day=a; openDate.mon=m;
void setYear(int y) {year=y;}
openDate.year=y;
int getDay() {return day;}
int getMonth() {return mon;} openDate.setDay(d); Need to access through
int getYear() {return year;} openDate.setMonth(m); public setter function of
}; openDate.setYear(y); Date object
}
void print(){
int main(){ cout<<"Acc No: "<<accNo<<"\n";
Account a; cout<<"Balance: "<<balance<<"\n";
a.setAccount(1);
cout<<"Opening Date: ";
a.setBalance(1000);
a.setOpenDate(15,2,2022); cout<<openDate.getDay()<<"-";
Need to access through
a.print(); cout<<openDate.getMonth()<<"-";
public setter function of
return 0; Output
Date object
} cout<<openDate.getYear() <<"\n";
}
};
Function Overloading
C C++
● Functions are either //In cstdlib.h
int abs(int i); //in stdlib.h
● member functions — float fabs(float f); //in
int abs(int i);
float abs(float f);
defined inside a class math.h long abs(long l);
● free functions — defined long labs(long l); //in stdlib.h //----------------------
in global scope //------------------------ int main(){
--- int i=-2;
● In C, every function has a int main(){ float f = -3.4;
unique name int i=-2; long l = -3400l;
float f = -3.4; cout<<abs(i)<<endl;
● C++ allows several long l = -3400l; cout<<abs(f)<<endl;
functions with the same printf("%d\n",abs(i)); cout<<abs(l)<<endl;
name printf("%f\n",fabs(f)); return 0;
printf("%ld\ }
n",labs(l));
return 0;
}
Overloading mechanism
⚫ Function are differentiated by their names and
argument list
⚫ For overloading, Argument list must vary in
⚫ Number of arguments
⚫ Types of arguments
⚫ Only return types can’t be used to differentiate
functions
Error!
Cannot be Overloaded
int main(){
Account a1, a2(2,2000);
return 0;
}
CPP Practice Problems: Complex Number
#include<iostream> int main(){
#include<math.h> Complex c1(3,4);//3+4i
using namespace std; Complex c2,c3,c4;
class Complex{ c2.setReal(5);
int a; //real part c2.setImaginary(10);
int b; //imaginary part
c1.print();
public:
cout<<"Mod of c2: ";
Complex(){a=0; b=0;}
Complex(int r, int i){a=r; b=i;}
cout<<c2.getModulus()<<endl;
~Complex(){cout<<"In destructor\n";} c3=c1.add(c2);
void setReal(int r){a=r;} c3.print();//8+14i
void setImaginary(int i){b=i;} c4=c1.multiply(c2);
int getReal(){return a;} c4.print();//-25+50i
int getImaginary(){return b;} return 0;
void print(){cout<<a<<"+"<<b<<"i"<<endl;} }
double getModulus(){return sqrt(a*a+b*b);}
Complex add(Complex c){
return Complex(a+c.getReal(),b+c.getImaginary());
}
Complex multiply(Complex c){
int real=a*c.getReal()-b*c.getImaginary();
int imaginary=a*c.getImaginary()+b*c.getReal();
return Complex(real,imaginary);
}
};
CPP Practice Problems: Point and Circle
class Point{ Point::Point(){x=y=0;}
double x,y; Point::Point(double px, double py){x=px; y=py;}
public: double Point::distance(Point p){
Point(); return sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y));
Point(double px, double py); }
double distance(Point p);
};
double PI=3.14;
class Circle{ Circle::Circle(Point c, double r){center=c; radius=r;}
Point center; double Circle::area(){return PI*radius*radius;}
double radius; double Circle::circumference(){
public: return 2*PI*radius;
Circle(Point c, double r); }
double area(); int Circle::isInsideCircle(Point p){
double circumference(); if(p.distance(center)<=radius)
int isInsideCircle(Point p); return 1;
int isInsideCircle(Circle c); else return 0;
}; }
int Circle::isInsideCircle(Circle c){
int main(){ if(center.distance(c.center)>=radius+c.radius)
Point p1(2,3), p2(4,6); return 1;
Circle c1(p1,4), c2(p2,2); else if(center.distance(c.center)<=radius-c.radius)
return -1;
cout<<c1.circumference()<<endl;
else if(center.distance(c.center)<=radius-c.radius)
cout<<c1.area()<<endl;
return -2;
cout<<c1.isInsideCircle(p2)<<endl; else return 0;
}
cout<<c1.isInsideCircle(c2)<<endl;
return 0;
}
Acknowledgement
This slide has been prepared by taking help from numerous resources. The notable contributors
are listed below.
1. The slides have been compiled and curated by Khaled Mahmud Shahriar, Assistant
Professor, CSE, BUET for CSE287 offered to the Department of MME.
2. Content and organization of many pages have been taken from the lecture slides and codes
of the course CSE110 offered to the Department of EEE that were -
i. primarily created by Johra Muhammad Moosa, Assistant Professor (on leave), CSE,
BUET and
ii. later modified by Madhusudan Basak, Assistant Professor, CSE, BUET
3. Most of the wonderful coding examples have been taken from the course CSE281 offered
to the Department of BME instructed by Rifat Shahriyar, Professor, CSE, BUET (course link
).
4. search and all the sites that it made available in response to the course related
queries. Some of the sites are: https://geeksforgeeks.org/, https://www.tutorialspoint.com,
https://www.w3schools.com and the list goes on …
Thank You ☺