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

Oop C++

The document discusses object oriented programming (OOP) concepts in C++ including classes, objects, encapsulation, and constructors. It explains that OOP models real world entities as objects that have states and behaviors. Classes define objects, and objects are instances of classes. The document also covers access specifiers like public and private, and how setter and getter functions are used to control access to class properties.

Uploaded by

niloypandit.1408
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Oop C++

The document discusses object oriented programming (OOP) concepts in C++ including classes, objects, encapsulation, and constructors. It explains that OOP models real world entities as objects that have states and behaviors. Classes define objects, and objects are instances of classes. The document also covers access specifiers like public and private, and how setter and getter functions are used to control access to class properties.

Uploaded by

niloypandit.1408
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

C Programming

Introduction to C++

Khaled Mahmud Shahriar


Assistant Professor
Department of CSE, BUET
What is C++?
• C++ is OOP language
• C++ is (almost exactly) a superset of C
• At a high level: C++ ~= C + OOP
• One strategy for learning C++:
1. Learn C – You have already done it
2. Learn (C++ - C)

2
Input Output in C++
#include<iostream> Will show error if these
using namespace std; two lines are omitted

int main(){
int i;
float j;
char c; Input 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 placed on the int main(){
output stream. double j=10.2324786, k=345.34375253;
cout<<"j="<<j<<endl;
Default: Max 6-digits;
• Most of the standard cout<<"k="<<k<<endl;
value rounded
manipulators are found in
cout<<fixed<<setprecision(5);
<iostream> cout<<"j="<<j<<endl;
• Manipulator that take arguments cout<<"k="<<k<<endl; Output
are defined in <iomanip>
cout<<scientific;
• Some manipulators are cout<<"j="<<j<<endl;
• endl, setw(size), setprecision(size) cout<<"k="<<k<<endl;
etc.
return 0;
}
C Programming

Object Oriented Programming (OOP) with C+


+

Khaled Mahmud Shahriar


Assistant Professor
Department of CSE, BUET
What is Object Oriented Programming (OOP)
• Object Oriented Programming (OOP) is an engineering approach for
building software systems
• Based on the concepts of classes and objects that are used for modelling the
real-world entities
• Object-oriented programs
• Consist of a group of cooperating objects
• Objects exchange messages for the purpose of achieving a common objective
• Implemented in object-oriented languages

Ref: https://www.slideshare.net/bgjeecourse/objectoriented-concepts-5576132
Principles of OOP
• Encapsulation
• Polymorphism
• Inheritance
• Abstraction
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
Encapsulation
• Mechanism that binds together code and the data it manipulates.
• Safe from outside interference and misuse
• Object is the device that supports encapsulation

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
• A class defines called instantiation
• Set of attributes • An object is a concrete instance of a
particular class
- also called state
- represented by variables
• Objects have states
• Behavior • Set of values associated to their
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; occupies no
class Account{
physical memory
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(){
Object declarations; occupies
Account a1, a2;
physical memory
return 0;
}
Access protection
• C++ class and struct have three levels of
protection
• public: visible to all clients
• private: visible only to class members private public
• protected: will be covered later accNo
balance
• Any member declared as public is accessible
through an object.
• Members declared as private can only be accessed setVals() print()
by a public member functions of the class.
• Access protection pertains only to clients.
• Inside the class, all members are visible.
Access from clients
• Compiler enforces the access protection 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 special #include<iostream>
using namespace std;
methods that are used to protect class Account{
data int accNo;
double balance;
• Setters are used to set values to public:
private properties of a class //setter functions
void setAccount(int a){ accNo=a; }
• Also known as mutators void setBalance(double b){ balance=b; }
//getter functions
• Getters are used to read values of int getAccNo(){ return accNo; }
private properties of a class double getBalance(){ return balance; }
};
• Also known as mutators
• Setters and Getters allow to control int main(){
Account a;
how important variables are updated a.setAccount(1);
and accessed a.setBalance(1000);
cout<<"Acc No: "<<a.getAccNo() <<"\n";;
cout<<Balance: "<<a.getBalance()<<"\n";
return 0;
}
Encapsulation : Revised
● Keeps code or data or both safe from outside
interference.
○ Declaring them private / protected according to
need
● Public parts of an object are used to provide a
controlled interface to the private elements
Constructor
• A constructor is a special member Won’t be covered in
this term!
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
int main(){ a default 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 Constructor
cout<<"In constructor of "<<accNo<<".\n";
}
};
int main(){
Account a1(1,1000), a2; This will generate a compile error as the
return 0; 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(){ Output
cout<<"Acc No: "<<accNo<<", Balance: "<<balance<<"\n";
}
(1,1000)
}; a1.Account
a2 .A cco unt(2,2000)
int main(){
Account a1(1,1000), a2(2,2000);
a1.print(); a2.~Accoun
t()
a2.print();
return 0; Destructors are called in the reverse a1.~Accoun
t()
} 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.\n";}
Account();
Account(int a, double b); void Account::setAccount(int a){accNo=a;}
//Destructor function void Account::setBalance(double b){ balance=b;}
~Account();
int Account::getAccNo(){return accNo;}
//setter functions double Account::getBalance(){return balance;}
void setAccount(int a);
void setBalance(double b); int Account::debit(double amount)
//getter functions {
int getAccNo(); if(accNo!=-1 && balance>=amount){
double getBalance(); balance=balance-amount;
return 1;
//other functions }
int debit(double amount); else return 0;
void credit(double amount); }
}; void Account::credit(double amount){
if(accNo!=-1) balance=balance+amount;
}
Object Assignment
• One object can be assigned to other if both are of same type
• Bitwise copy of members variables are done
• The two objects will remain completely separate
• It is not sufficient that the object types are physically similar
• Type name should be similar
Example: Object Assignment
#include<iostream>
using namespace std;
class Account{
int accNo;
double balance;
public:
Account(){accNo=-1; balance=-1;}
Account(int a, double b){accNo=a; balance=b;}
void print(){
cout<<"Acc No: "<<accNo<<", Balance: "<<balance<<"\n";
}
};

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);

a=b; Compile Error!

return 0;
}
Arrays of Objects
• Objects can be arrayed
• Array objects can be initialized if constructor available
class Account{
int accNo; Example: Arrays of Objects Output
double balance;
public: 1
Account(){
cout<<"In default constructor.\n";
accNo=-1; balance=-1; 2
}
Account(int a, double b){
accNo=a; balance=b; 3
cout<<"In constructor of "<<accNo<<".\n";
}
~Account(){ 4
cout<<"In destructor of "<<accNo<<".\n";
}
void print(){ 5
cout<<"Acc No: "<<accNo<<", ";
cout<<"Balance: "<<balance<<"\n";
} 6
};

int main(){ 3 ways of initializing 7


1 Account a1[3];
for(int i=0;i<3;i++) a1[i].print(); 2 an array of objects
3 Account a2[3]={Account(1,100),Account(2,200),Account(3,300)}; 8
for(int i=0;i<3;i++) a2[i].print(); 4
5 Account a3[3]={{10,1000},{20,2000},{30,3000}};
for(int i=0;i<3;i++) a3[i].print(); 6 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(){ Output
cout<<"In the destructor of "<<accNo<<"\n";
}
void transferFrom(Account a, double b){
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"; Output
}
Account transferFrom(Account a, double b){
balance=balance+b; Object a can directly access object b’s private
a.balance=a.balance-b; data, as they are of to the same class
return a;
} Object as a return value
void print(){
Balance
cout<<"Acc No: "<<accNo<<", Balance: "<<balance<<"\n"; 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; openDate.year=y;
void setYear(int y) {year=y;}
int getDay() {return day;} openDate.setDay(d);
Need to access through public
int getMonth() {return mon;} openDate.setMonth(m);
setter function of Date object
int getYear() {return year;} openDate.setYear(y);
}; }
void print(){
int main(){ cout<<"Acc No: "<<accNo<<"\n";
Account a;
cout<<"Balance: "<<balance<<"\n";
a.setAccount(1);
a.setBalance(1000); cout<<"Opening Date: ";
a.setOpenDate(15,2,2022); cout<<openDate.getDay()<<"-";
Need to access through public
a.print(); cout<<openDate.getMonth()<<"-";
Output setter function of Date object
return 0;
} cout<<openDate.getYear() <<"\n";
}
};
CPP Practice Problem
Write a C++ Program To Calculate Electricity Bill Of Person using Class. Here’s a Simple
Program To Calculate Electricity Bill Of Person using Class in C++ Programming Language.

Algorithm for Calculating Electricity Bill :


● To Calculate Electricity Bill Of Person using Class,first we have to create and call get( )
function to take input details of the customer.
● After get( ) , we create and call a new function i.e calc_bill( ) to calculate the total bill of
the customer on the behalf of units consumed by the customer .
● At last , we call the put( ) function to print or display customer or person electricity bill
on the screen.

Here are some tarrifs set per unit consumption of electricity to the customer.
Unit tarrif :
first 100 units-> RS. 1.20 per unit
next 200 units -> RS. 2 per unit
above 300 units -> RS. 3 per unit
Using new and delete
• C++ introduces two operators for dynamically allocating and
deallocating memory

• p_var = new type //type *p_var;


• new returns a pointer to dynamically allocated memory that is sufficient to
hold a data of type
• delete p_var
• releases the memory previously allocated by new

• Memory allocated by new must be released using delete

41
Using new and delete
• In case of insufficient memory, new can report failure in two ways
• By returning a null pointer
• By generating an exception
• The reaction of new in this case varies from compiler to compiler

42
Using new and delete
• Advantages
• Automatically allocates enough memory to hold an object of the specified
type, do not need to use sizeof operator
• Automatically returns a pointer of the specified type, do not to use an explicit
type cast
• Both new and delete can be overloaded
• In case of objects, new dynamically allocates the object and calls its
constructor
• In case of objects, delete calls the destructor of the object

43
Constructor and Destructor
#include <iostream>
using namespace std;

class Rectangle {
int *width, *height;
public:
Rectangle(){};
Rectangle(int, int);
~Rectangle ();
int area () {return (*width * *height);}
};

Rectangle::Rectangle (int a, int b) {


width= new int;
height = new int;
*width = a;
*height = b;
}
44
Constructor and Destructor
Rectangle:: ~Rectangle () {
delete width;
delete height;
}

int main () {
Rectangle recta (3,4), rectb (5,6);
cout << "recta area: " << recta.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}

45
Object Pointer
int main () {
Rectangle a, *b, *c;

b= new Rectangle(3, 4);


c= &a;

delete b;
return 0;
}

46
More About new and delete
• Dynamically allocated objects can be given initial values

• int *p = new int;


• Dynamically allocates memory to store an integer value which contains garbage value

• int *p = new int(10);


• Dynamically allocates memory to store an integer value and initializes that memory to 10
• Note the use of parenthesis ( ) while supplying initial values

47
More About new and delete
• class A{ int x; public: A(int n) { x = n; } };

• A *p = new A(10);
• Dynamically allocates memory to store a A object and calls the constructor A(int n) for this
object which initializes x to 10

• A *p = new A;
• It will produce compiler error because in this example class A does not have a default
constructor

48
More About new and delete
• We can also create dynamically allocated arrays using new
• But deleting a dynamically allocated array needs a slight change in the use of
delete

• It is not possible to initialize an array that is dynamically allocated


• int *a= new int[10];
• Creates an array of 10 integers
• All integers contain garbage values
• Note the use of square brackets [ ]

• delete [ ] a;
• Delete the entire array pointed by a
• Note the use of square brackets [ ]
49
More About new and delete
• We can also create dynamically allocated arrays using new
• But deleting a dynamically allocated array needs a slight change in the use of
delete

• It is not possible to initialize an array that is dynamically allocated


• int *a= new int[10];
• Creates an array of 10 integers
• All integers contain garbage values
• Note the use of square brackets [ ]

• delete [ ] a;
• Delete the entire array pointed by a
• Note the use of square brackets [ ]
50
More About new and delete
• It is not possible to initialize an array that is dynamically allocated
• In order to create an array of objects of a class, the class must have a
default constructor
class A { class A {
int x; int x;
public: public:
A(int n) { x = n; } }; A() { x = 0; }
A(int n) { x = n; } };
A *array = new A[10]; A *array = new A[10]; // no error
// compiler error // use array
delete [ ] array;

51
More About new and delete
• A *array = new A[10];
• The default constructor is called for all the objects.
• delete [ ] array;
• Destructor is called for all the objects present in the array.

52
Acknowledgement
All these slides of this course have been prepared by taking help from numerous
resources. The notable contributors are listed below.
1. 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
2. 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).
3. 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 ☺

You might also like