Object Oriented Programming With C++
Object Oriented Programming With C++
Object Oriented Programming With C++
with C++
Software Crisis
• New approaches in the s/w design
– Dynamic development in technology
– Quick emergence of new tools and technologies
• Increasing complexity of software system
• Highly competitive s/w industry
Other problems
• Representation of real life entities in system
design
• Design system with open interfaces
• Ensure reusability ,extensibility, correctness,
portability, security, integrity, user friendliness
• Modules tolerant to changes
• Improve s/w production and reduce cost
• Improve quality
Evolution
• Modular programming
• Structured programming
• Top down programming
• Bottom up programming
• Functional programming
– Fail to produce the desired result of bug free, easy
to maintain and reusable programs.
“As complexity increase, architecture dominates
the basic material” –alan kay
• Necessitates incorporation of sound
construction techniques and program
structures that are easy to comprehend,
implement and modify
Procedure oriented programming
•
Pop
• Emphasis is on doing things (algorithms)
• Programs are divided into smaller units called
functions.
• Most of the functions share global data
• Data move openly around the system from
function to function.
• Function transforms data from on form to another.
• Top down approach.
Pop vs oop
•
Object oriented programming
• Emphasis is on data rather than procedures
• Programs are divided into objects
• Data structures are designed such that they
characterize the objects.
• Functions that operate on the data are tied
together in the Data structure
• Data is hidden and cannot be accessed by
external functions
• Objects may communicate with each other through
functions
• New data and functions can be easily added whenever
necessary.
• Bottom up approach in program design .
• “Approach that provides a way of modularizing
programs by creating partitioned memory area for
both data and functions that can be used as templates
for creating copies of such modules on demand”
Basic concepts
• Objects
• Classes
• Data abstraction and encapsulation
• Inheritance
• Polymorphism
• Dynamic binding
• Message passing
Car example
•
benefits
• Eliminates redundancy and extends reuse
• Saves dev time leads to productivity.
• Builds secure programming
• Maps object in the problem domain to
programs
• Easily scalable from small to large
• Complexity can be easily managed.
Applications
• Real time systems
• Simulation and modelling
• Object oriented databases
• AI and expert systems
• Parallel programming and neural networks
• Office automation and cad/cam tools
A simple C++ program
• Comments
• Output operator
• Iostream file
• Namespace
• Return type
Sample program
#include <iostream>
using namespace std;
int main()
{
int firstNumber, secondNumber, sumOfTwoNumbers;
// Prints sum
cout << firstNumber << " + " << secondNumber << " = " <<
sumOfTwoNumbers;
return 0;
• Input operator
• Variables
• Cascading of I/o operators
// classes example
#include <iostream>
using namespace std;
class Rectangle {
int width, height;
public:
void set_values (int,int);
int area() {return width*height;}
};
void Rectangle::set_values (int x, int y) {
width = x;
height = y;
}
int main () {
Rectangle rect;
rect.set_values (3,4);
cout << "area: " << rect.area();
return 0;
}
Structure of C++ program
Tokens expressions and control structures
Tokens
• Smallest individual units in a program
– Keywords
– Identifiers
– Constants
– Strings and operators
• Keywords
– Explicitly reserved identifiers and cannot be used
as names for variables or user defined program
elements
Basic Data Type
Functions
• Argument Passing
– Pass by value
– Pass by reference
– Pass by address
• Inline Function
– C++ provides an inline functions to reduce the
function call overhead.
– Inline function is a function that is expanded in
line when it is called.
– When the inline function is called whole code of
the inline function gets inserted or substituted at
the point of inline function call.
– This substitution is performed by the C++ compiler
at compile time.
– Inline function may increase efficiency if it is small.
– in lining is only a request to the compiler, not a
command.
– Compiler can ignore the request in such
circumstances like:
• If a function contains a loop. (for, while, do-while)
• If a function contains static variables.
• If a function is recursive.
• If a function return type is other than void, and the
return statement doesn’t exist in function body.
• If a function contains switch or goto statement.
#include <iostream>
using namespace std;
inline int cube(int s)
{
return s*s*s;
}
int main()
{
cout << "The cube of 3 is: " << cube(3) << "\n";
return 0;
}
//Output: The cube of 3 is: 27
Function overloading
• Function overloading is a feature in C++ where
two or more functions can have the same
name but different parameters.
• Function overloading can be considered as an
example of polymorphism feature in C++.
#include <iostream>
using namespace std;
int absolute(int);
float absolute(float);
int main() {
int a = -5;
float b = 5.5;
cout << "Absolute value of " << a << " = " << absolute(a) << endl;
cout << "Absolute value of " << b << " = " << absolute(b);
return 0;
}
int absolute(int var) {
if (var < 0)
var = -var;
return var;
}
float absolute(float var){
if (var < 0.0)
var = -var;
return var;
}
• In C++ programming, you can provide default
values for function parameters.
• . 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.
Default arguments
#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;
}
• const int* u;
– Here, u is a pointer that can point to a const int type
variable.
• char const* v;
– still it has the same meaning. In this case also, v is a
pointer to an char which is of const type.
// Default Constructor
construct()
{
a = 10;
b = 20;
}
};
int main()
{
// Default constructor called automatically
// when the object is created
construct c;
cout << "a: "<< c.a << endl << "b: "<< c.b;
return 1;
}
• Parameterized constructor
– It is possible to pass arguments to constructors.
– these arguments help initialize an object when it is
created.
– To create a parameterized constructor, simply add
parameters to it the way you would to any other
function.
– When you define the constructor’s body, use the
parameters to initialize the object.
• Copy constructor
#include<iostream>
using namespace std;
class Point
{
private: int main()
int x, y; {
public: // Constructor called
// Parameterized Constructor Point p1(10, 15);
Point(int x1, int y1)
{ // Access values assigned by
x = x1; constructor
y = y1; cout << "p1.x = " << p1.getX()
} << ", p1.y = " << p1.getY();
// Increase every time object is created Box Box1(3.3, 1.2, 1.5); // Declare box1
objectCount++; Box Box2(8.5, 6.0, 2.0); // Declare box2
}
double Volume() { // Print total number of objects after creating object.
return length * breadth * height; cout << "Final Stage Count: " << Box::getCount() <<
} endl;
static int getCount() {
return objectCount; return 0;
} }
Case 1:Friend functions
• A friend function is a function that can access the
private members of a class as though it were a
member of that class.
• A friend function may be either a normal function,
or a member function of another class.
• To declare a friend function, simply use
the friend keyword in front of the prototype of the
function you wish to be a friend of the class.
/* C++ program to int func(Distance d){
demonstrate the working of //function definition
friend function.*/ d.meter=10; //accessing private data
from non-member function
return d.meter;
#include <iostream> }
using namespace std;
int main(){ Distance D;
cout<<"Distace: "<<func(D);
class Distance { system("pause");
private: return 0;
}
int meter;
public:
Distance(): meter(0){ }
friend int
func(Distance); //friend
function
};
Case 2:Multiple friends
• A function can be a friend of more than one
class at the same time
– PrintWeather is a friend of both classes, it can access
the private data from objects of both classes.
– class prototype that tells the compiler that we are
going to define a class called Humidity in the future.
– Without this line, the compiler would tell us it
doesn’t know what Humidity is when parsing the
prototype for PrintWeather() inside the Temperature
class.
class Humidity;
class Temperature
{
private:
int m_temp;
public:
Temperature(int temp=0) { m_temp = temp; }
class Humidity
{
private:
int m_humidity;
public:
Humidity(int humidity=0) { m_humidity = humidity; }
int main()
{
Humidity hum(10);
Temperature temp(12);
printWeather(temp, hum);
return 0;
}
Case 3: Friend member functions
• Instead of making an entire class a friend, you
can make a single member function a friend.
• This is done similarly to making a normal
function a friend, except using the name of
the member function with the className::
prefix included
– (e.g. Display::displayItem).
class Storage; // forward declaration for class Storage
class Display
{
private:
bool m_displayIntFirst;
public:
Display(bool displayIntFirst) { m_displayIntFirst = displayIntFirst; }
void displayItem(Storage &storage); // forward declaration above needed for this declaration line
};
// Make the Display::displayItem member function a friend of the Storage class (requires seeing the full declaration of class Display,
as above)
friend void Display::displayItem(Storage& storage);
};
// Now we can define Display::displayItem, which needs to have seen the full declaration of
class Storage
void Display::displayItem(Storage &storage)
{
if (m_displayIntFirst)
std::cout << storage.m_nValue << " " << storage.m_dValue << '\n';
else // display double first
std::cout << storage.m_dValue << " " << storage.m_nValue << '\n';
}
int main()
{
Storage storage(5, 6.7);
Display display(false);
display.displayItem(storage);
return 0;
}
Friend classes
public:
Display(bool displayIntFirst) { m_displayIntFirst = displayIntFirst; }
int main()
{
Storage storage(5, 6.7);
Display display(false);
display.displayItem(storage);
return 0;
}
Passing objects as arguments
• The objects of a class can be passed as arguments to member
functions as well as nonmember functions either by value or by
reference.
• When an object is passed by value,
– a copy of the actual object is created inside the function. This copy is
destroyed when the function terminates. A
– Any changes made to the copy of the object inside the function are not
reflected in the actual object.
• In pass by reference,
– only a reference to that object (not the entire object) is passed to the
function.
– changes made to the object within the function are also reflected in the
actual object.
• Whenever an object of a class is passed to a
member function of the same class, its data
members can be accessed inside the function
using the object name and the dot operator.
• However, the data members of the calling
object can be directly accessed inside the
function without using the object name and
the dot operator.
#include<iostream.h> void weight :: putdata ()
class weight {
{ cout<<kilogram<<" Kgs. and"<<gram<<"
gros.\n";
int kilogram;
}
int gram; void weight :: sum_weight(weight
public: wl,weight w2)
void getdata (); {
void putdata (); gram = wl.gram + w2.gram;
void sum_weight (weight,weight) ; kilogram=gram/1000;
gram=gram%1000;
};
kilogram+=wl.kilogram+w2.kilogram;
void weight :: getdata() }
{
cout<<"/nKilograms:";
cin>>kilogram;
cout<<"Grams:";
cin>>gram;
}
int main ()
w3.sum_weight(wl,w2);
{
cout<<"/n Weight #1 = ";
weight wl,w2 ,w3;
wl.putdata();
cout<<"Enter weight in kilograms
and grams\n"; cout<<"Weight #2 = ";
w2.putdata();
cout<<"\n Enter weight #1" ;
cout<<"Total Weight = ";
wl.getdata();
w3.putdata();
cout<<" \n Enter weight #2" ;
return 0;
w2.getdata();
}
Array of Objects
• an array of a class type is also known as an
array of objects.
• The array of type class contains the objects of
the class as its individual elements.
#include <iostream> int main()
#include <string> {
using namespace std; Student st[5];
class Student for( int i=0; i<5; i++ )
{ {
string name; cout << "Student " << i + 1 << endl;
int marks; cout << "Enter name" << endl;
public:
st[i].getName();
cout << "Enter marks" << endl;
void getName(){
st[i].getMarks();
getline( cin, name );
}
}
void getMarks(){
cin >> marks; for( int i=0; i<5; i++ )
} {
void displayInfo(){ cout << "Student " << i + 1 << endl;
cout << "Name : " << name << endl; st[i].displayInfo();
cout << "Marks : " << marks << endl; }
} return 0;
}; }
“This” pointer
• “When a member function is called, how does C++ keep
track of which object it was called on?”
public:
Something(int data)
{
this->data = data;
}
};
• if a constructor (or member function) has a
parameter with the same name as a member
variable, you can disambiguate them by using “this”:
• “data” refers to the parameter, and “this->data”
refers to the member variable.
• Although this is acceptable coding practice, using
the “m_” prefix on all member variable names
provides a better solution by preventing duplicate
names altogether!
Constructor Overloading
• Constructor can be overloaded in a similar way as
function overloading.
• Overloaded constructors have the same name (name
of the class) but different number of arguments.
• Depending upon the number and type of arguments
passed, specific constructor is called.
• Since, there are multiple constructors present,
argument to the constructor should also be passed
while creating an object.
#include <iostream> int main()
using namespace std; {
class Area{ Area A1, A2(2, 1);
private: int temp;
cout << "Default Area when no
int length; int breadth;
argument is passed." << endl;
public:
Area(): length(5), breadth(2) { } temp = A1.AreaCalculation();
Area(int l, int b): length(l), breadth(b){ } A1.DisplayArea(temp);
void GetLength() {
cout << "Enter length and breadth "; cout << "Area when (2,1) is passed
as argument." << endl;
cin >> length >> breadth;
} temp = A2.AreaCalculation();
int AreaCalculation() { A2.DisplayArea(temp);
return length * breadth; return 0;
} }
void DisplayArea(int temp){
cout << "Area: " << temp << endl;}
};
Copy constructor
• A copy constructor is a member function which initializes an
object using another object of the same class.
• A copy constructor has the following general function prototype:
ClassName (const ClassName &old_obj);
int x; // Global x
int main()
{
int x = 10; // Local x
cout << "Value of global x
is " << ::x;
cout << "\nValue of local x
is " << x;
return 0;
}
To define a function outside a class.
#include<iostream>
using namespace std;
class A
{
public:
// Only declaration
void fun();
};
// Definition outside class using ::
void A::fun()
{
cout << "fun() called";
}
int main()
{
A a;
a.fun();
return 0;
}
To access a class’s static variables.
#include<iostream>
using namespace std;
class Test
{ int Test::x = 1;
static int x; int Test::y = 2;
public:
static int y; int main()
{
// Local parameter 'a' hides class memberTest obj;
// 'a', but we can access it using ::
int x = 3 ;
void func(int x)
{
obj.func(x);
// We can access class's static variable
// even if there is a local variable cout << "\nTest::y = " << Tes
cout << "Value of static x is " << Test::x;
return 0;
cout << "\nValue of local x is " <<
} x;
}
};
In case of multiple Inheritance:
If same variable name exists in two ancestor classes, we can use scope
resolution operator to distinguish.
#include<iostream>
class C: public A, public B
using namespace std;
{
public:
class A
void fun()
{
{
protected:
cout << "A's x is " << A::x;
int x;
cout << "\nB's x is " << B::x;
public:
}
A() { x = 10; }
};
};
int main()
class B
{
{
C c;
protected:
c.fun();
int x;
return 0;
public:
}
B() { x = 20; }
};
Dynamic objects
• Memory for the variables is allocated in two
ways
– Static allocation
• Decision to allocate memory for the variable is taken
during compile time
– Dynamic allocation
• Decision to allocate memory for the variable is taken
during execution
• To allocate memory dynamically “new” operator
is used in C++
• Syntax:
– Pointer= new data_type;
#include<iostream>
int main()
{
int *p;
p=new int;
*p=89;
cout<<*p;
return 0;
}
New operator on any array
#include<iostream>
int main()
{
int n, sum, i ,*p;
cout<<“enter the numner of elements”<<“\n”;
cin>>n;
p=new int [n];
cout<<“enter the array elements”;
for(i=0;i<n;i++)
{
cin>>p[i];
}
sum=0;
for(i=0;i<n;i++)
{
sum=sum+p[i];
}
cout<<“result of adding array elemnets is:”<<sum;
}
Delete operator
• To deallocate the dynamically allocated memory, “delete” operator is
used.
• Syntax
– delete pointer;
#include<iostream>
int main()
{
int *p;
p=new int;
*p=89;
cout<<*p;
delete p;
return 0;
}
#include<iostream>
int main()
{
int n, sum, i ,*p;
cout<<“enter the number of elements”<<“\n”;
cin>>n;
p=new int [n];
cout<<“enter the array elements”;
for(i=0;i<n; i++)
{
cin>>p[i];
}
sum=0;
for(i=0;i<n; i++)
{
sum=sum+p[i];
}
cout<<“result of adding array elements is:”<<sum;
delete[] p;
}
void print()
#include <iostream>
{
#include <string> cout<<"roll no is "<<rollno;
using namespace std; cout<<"name is "<<name;
class student }
};
{
int main ()
private: {
int rollno; student *ps=new student;
string name; (*ps).get();
(*ps).print();
public:
delete ps;
student():rollno(0),name("") return 0;
{} }
student(int r, string n): rollno(r),name (n) ---------------------------------------------------------------
int main ()
{}
{
void get() student ps;
{ student *p;
cout<<"enter roll no"; p=&ps;
cin>>rollno;
p->get();
cout<<"enter name"; p->print();
cin>>name;
} return 0;
}