Unit-I Oop RBK
Unit-I Oop RBK
Foundations of OOP
Procedural Oriented Programming
Language
• Conventional programming, using high-level
language such as COBOL, FORTRAN and C are
commonly known as Procedure Oriented
Programming (POP) languages.
Function-4 Function-5
Operations
Data
OBJECT OBJECT
Operations Operations
In POP, Importance is not given to data but to In OOP, Importance is given to the data rather than
Importance functions as well as sequence of actions to be procedures or functions because it works as a real
done world
Approach POP follows Top Down approach OOP follows Bottom Up approach
In POP, Data can move freely from function to In OOP, objects can move and communicate with
Data Moving
function in the system each other through member functions
To add new data and function in POP is not so OOP provides an easy way to add new data and
Expansion
easy function
In POP, Most function uses Global data for In OOP, data can not move easily from function to
Data Access sharing that can be accessed freely from function function, it can be kept public or private so we can
to function in the system control the access of data
POP does not have any proper way for hiding OOP provides Data Hiding so provides more
Data Hiding
data so it is less secure security
Examples Example of POP are : C, VB, FORTRAN, Pascal Example of OOP are : C++, JAVA, VB.NET, C#.NET
Fundamentals of OOP
• Objects
• Classes
• Encapsulation
• Data Abstraction
• Inheritance
• Polymorphism
• Dynamic Binding
• Message Passing
//Program: Basic Program
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Include Files
Class Definition
#include <iostream>
#include <string>
using namespace std; int main() {
Car carObj1;
carObj1.brand = "BMW";
class Car { carObj1.model = "X5";
public: carObj1.year = 1999;
string brand;
string model; Car carObj2;
int year; carObj2.brand = "Ford";
carObj2.model = "Mustang";
};
carObj2.year = 1969;
cout << carObj1.brand << " " << carObj1.model << " " <<
carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " <<
carObj2.year << "\n";
return 0;
}
Output:
BMW X5 1999
Ford Mustang 1969
Object
Operation
Operation
Example: StudentObject
Enroll()
st_name
st_id Displayinfo()
Performance()
branch
semester
Result()
Class
• Class is a collection of objects.
Class
Encapsulation
• The wrapping up of data and functions into a
single unit (called class) is known as
encapsulation.
Parent class
Or
Base class
Point
Child class
Or
Derived
class
Line
Polymorphism
• The ability to take more than one form.
+
Dynamic Binding
• Dynamic Binding is the process of linking of
the code associated with a procedure call at
the run-time
Message Passing
• The process of invoking an operation on an
object.
• In response to a message the corresponding
method is executed in the object
Message Passing
StudentObject FacultyObject
Performance
MgmtObject Performance
Result
Variable Declaration
• A variable defines a location in the memory that
holds a value which can be modified later.
• Syntax:
type variable_list;
• In the above syntax "type" refers to any one of the
C++ data types.
Declaring Variables
• Variables in C++ should be declared before they are used in the
code block.
#include <iostream.h>
void main()
{
int n = 10;
cout << "Integer value is:"<< n << '\n';
}
• Result:
Integer value is: 10
In the above example "n" is an integer variable declared
using return type "int".
Rules for Naming variables in C++
• Always the first character of a variable must be a
letter or an underscore.
• The variable name cannot start with a digit.
• Other characters should be either letters, digits,
underscores.
• There is no limit for the length of variables.
• Declared keywords cannot be used as a variable
name.
• Upper and lower case letters are distinct.
Variable Scope
• A scope is a region of the program and broadly
speaking there are three places, where
variables can be declared:
– Inside a function or a block which is called local
variables,
– In the definition of function parameters which is
called formal parameters
– Outside of all functions which is called global
variables.
Local variables
• Parameters and variables declared inside the
definition of a function are local.
• They only exist inside the function body.
• Once the function returns, the variables no
longer exist!
Example Using Local Variables:
#include <iostream.h>
int main ()
{ // Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
Global Variables
• We can declare variables outside of any
function definition – these variables are
global variables.
• Any function can access/change global
variables.
• Example: flag that indicates whether
debugging information should be printed.
Example Using Global and Local Variables
#include <iostream>
// Global variable declaration:
int g;
int main ()
{ // Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
Constants (const)
• Constants refer to fixed values that the
program may not alter
• Defining Constants:
• Using #define preprocessor.
• Using const keyword.
The #define Preprocessor:
• Following is the form to use #define preprocessor to define a
constant:
#define identifier value
Example
#include <iostream>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{ int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
Result: 50
}
The const Keyword:
• use const prefix to declare constants with a specific type as follows:
const type variable = value;
Example:-
#include <iostream.h>
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0; Output:50
}
Reference Variable
• Variable name as a label attached to the
variable's location in memory.
• Reference as a second label attached to that
memory location.
• Access the contents of the variable through
either the original variable name or the
reference.
• Syntax:
Data-type & reference name = variable name
• For example
int i = 17;
• We can declare reference variables for i as follows.
int& r = i;
the & in this declaration is as reference.
• Read declaration as "r is an integer reference
initialized to i"
Example
#include <iostream>
int main ()
{
// declare simple variables
int i; double d; Output:
// declare reference variables Value of i : 5
int& r = i; Value of i reference : 5
double& s = d; Value of d : 11.7
Value of d reference : 11.7
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;
return 0;
}
Comments in C++
• Program comments are explanatory
statements that you can include in the C++
code that you write and helps anyone reading
it's source code.
• C++ supports single-line and multi-line
comments. All characters available inside any
comment are ignored by C++ compiler.
• C++ comments start with /* and end with */.
For example:
/* This is a comment */
/* C++ comments can also
* span multiple lines
*/
• A comment can also start with //, extending to the
end of the line.
• For example:
#include <iostream.h>
main()
{
cout << "Hello World"; // prints Hello World
return 0;
}
Output : Hello World
Default Parameter
• C++ allows to call function without specifying all
its arguments
• In such cases, the function assigns default value
to the parameter which does not have a matching
argument in the function call.
• Default values are specified when function is
declared.
• The compiler looks at the prototype to see how
many arguments a function uses and alerts the
program for possible default values.
• The default value is specified in a manner
syntactically similar to a variable initialization.
• Add default values from right to left.
• Cannot provide a default value in the middle
of an argument list.
Default parameter (Example)
float amount(float principal, float period, float rate=0.15);
Default value 0.15 to parameter rate
Function call like
value = amount (5000,7); //one parameter missing
Passes 0.15 to rate
Now,
value =amount(5000,7,0.12) //no missing argument
Passes explicit value 0.12 to rate
#include<iostream.h> Output:
#include<conio.h> Enter Length:6
int vol(int=1,int=2,int=3); Enter width:5
main() { Enter height: 9
clrscr(); Volume with no argument passed =6
int length; int width; int height; Volume with one argument passed=36
int volume;
cout<<"\n Enter length = ";
cin>>length;
cout<<"\n Enter width = "; int vol(int l,int h,int w)
cin>>width; {
cout<<"\n Enter heigth = "; return l*h*w;
cin>>height; }
volume=vol();
cout<<"\n Volume with no argument passed ="<<volume;
volume=vol(length);
cout<<"\n Volume with one argument passed = "<<volume;
volume=vol(length,width);
getch();
return 0; }
Data Types
C++ supports the following data types:
• Integer
• Character
• Boolean
• Floating Point
• Double Floating Point
• Valueless or Void
• Wide Character
Data Types
2. Derived Data Types: Derived data types that are
derived from the primitive or built-in datatypes are
referred to as Derived Data Types. These can be of
four types namely:
• Function
• Array
• Pointer
• Reference
Data Types
3. Abstract or User-Defined Data Types: Abstract or
User-Defined data types are defined by the user itself.
Like, defining a class in C++ or a structure. C++
provides the following user-defined datatypes:
• Class
• Structure
• Union
• Enumeration
• Typedef defined Datatype
Datatype Modifiers
Datatype Modifiers
Data type modifiers available in C++ are:
• Signed
• Unsigned
• Short
• Long
Datatype Modifiers
Data Type Size (in bytes) Range
-2,147,483,648 to
int 4
2,147,483,647
-2,147,483,648 to
long int 4
2,147,483,647
0 to
unsigned long long int 8
18,446,744,073,709,551,615
#include <iostream>
#include <limits.h>
using namespace std;
int main()
{
cout << "Size of char : " << sizeof(char) << " byte" << endl;
cout << "char minimum value: " << CHAR_MIN << endl;
cout << "char maximum value: " << CHAR_MAX << endl;
cout << "Size of int : " << sizeof(int) << " bytes"<< endl;
cout << "Size of short int : " << sizeof(short int) << " bytes" << endl;
cout << "Size of signed long int : "
<< sizeof(signed long int) << " bytes" << endl;
cout << "Size of unsigned long int : “ << sizeof(unsigned long int)
<< " bytes" << endl;
cout << "Size of float : " << sizeof(float) << " bytes“ << endl;
cout << "Size of double : " << sizeof(double) << " bytes" << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << " bytes" <<
endl;
return 0;
Output:
• Syntax:
inline return_type func_name(formal parameters)
{
function body
}
Inline Functions
• Situations where inline expansion not work /
conditions for inline function:
– Function should not have any return statement, if
a loop, a switch, or a goto exists
– Function should not be recursive
– Function length should be small
– Function should not contain static variable
Example
void main()
#include<iostream.h>
{
#include<conio.h>
line obj;
float val1,val2;
class line
clrscr();
{
cout<<"Enter two values:";
public:
cin>>val1>>val2;
inline float mul(float x,float y)
cout<<"\nMultiplication value is:“;
{
cout<<obj.mul(val1,val2);
return(x*y);
cout<<"\n\nCube value is:”;
}
cout<<obj.cube(val1)<<"\
inline float cube(float x)
t"<<obj.cube(val2);
{
getch();
cout<<(x*x*x);
}
}
};
Inline Function
• Advantages
Shorter execution time
Does not require function calling overhead
Saves time
Memory Management Operator
• C++ supports two unary operators new and delete
operators that perform the task of allocating and
freeing the memory in a better and easier way.
• These operators manipulate memory on the free
store, they are also known as free store operators.
• Objects can be created by using new and deleted
by using delete operator.
• Syntax:
Pointer variable = new data-type
Pointer
• A pointer is a variable that stores the memory
address as its value.
cout << &food << "\n"; // Output the memory address of food
cout << ptr << "\n"; // Output the memory address of food with the pointer
return 0;
}
Output:
Pizza
0x6dfed4
0x6dfed4
Example
Int *p=new int;
Float *q=new float;
• Suppose
*p=25
*q=7.5
• int* p = new int(25);
• float* q = new float(75.25);
• pointer-variable = new data-type(value);
Example
• pointer-variable = new data-type[size];
• a new operator is also used to allocate a
block(an array) of memory of type data type.
Example:
• int *p = new int[10]
• Data object no longer needed, it is destroyed
to release memory space for reuse.
• Syntax
delete pointer variable
Example :
delete q;
delete p;
Example:
int main()
{
float PI = 3.14;
int num = 100;
cout << "Entering a new line." << endl;
cout << setw(10) << "Output" << endl;
cout << setprecision(10) << PI << endl;
cout << setbase(16) << num << endl; //sets base to 16
}
Output:
Entering a new line.
3.140000105
64
Defining Class
Class Specification
• Syntax:
class class_name
{
Data members
Members functions
};
Class Specification
• class Student
{
int st_id; Data Members or Properties of
char st_name[]; Student Class
};
Class Specification
• Visibility of Data members & Member functions
Public –
Accessed by member functions and all other non-member
functions in the program.
Private –
Accessed by only member functions of the class.
Protected –
Similar to private, but accessed by all the member functions of
immediate derived class
Default –
All items defined in the class are private.
Class Specification
• class Student
{
int st_id;
char st_name[]; private / default
void read_data(); visibility
void print_data();
};
Class Specification
• class Student
{
public:
int st_id;
char st_name[]; public visibility
public:
void read_data();
void print_data();
};
Class Specification
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
Class Objects
• Object Instantiation:
The process of creating object of the type class
• Syntax:
class_name obj_name;
e o b j ect of the
singl
ex: Student st; Creat es a
tudent!
type S
St_id, St_name
void read_data( )
void print_data( )
Class Object
• More of Objects
ex: Student st1;
Student st2;
Student st3;
Class Objects
10,Rama 20, Stephen
st1 st2
55, Mary
void read_data( )
void print_data( )
st3
Accessing Data Members
(inside the class)
• Syntax: (single object)
data_member;
ex: st_id;
Accessing Data & Members Functions
(outside the class)
• Using dot (.) operator
• Syntax: (single object)
obj_name . datamember;
obj_name . Member_function(actual param)
e.g. : st.st_id;
st.read_data();
Defining Member Functions
(Inside the class definition)
class Car {
public:
int speed(int maxSpeed);
};
int main() {
Car myObj;
cout << myObj.speed(200);
return 0; Output: 200
Arrays of Objects
• Several objects of the same class can be
declared as an array and used just like an array
of any other data type.
obj_name[i] . datamember;
ex: st[i].st_id;
Accessing Member Functions
• Syntax: (single object)
obj_name . Memberfunction(act_parameters);
ex: st.read( );
• Syntax:(array of objects)
obj_name[i] . Memberfunction(act_parameters);
ex: st[i].read( );
Inline Functions with Class
• Syntax: (Inside the class definition)
inline ret_type fun_name(formal parameters)
{
function body
}
Inline Functions with Class
• Syntax: (Outside the class definition)
inline ret_type class_name::fun_name (formal
parameters)
{
function body
}
Static Data Members
• Static data members of a class are also known
as "class variables“.
Syntax:
class class_name
{
public:
static ret_dt fun_name(formal parameters);
};
int main()
{
#include < iostream>
test t1,t2;
Class test
t1.setcode();
{
t2.setcode();
Int code;
test::showcount();
Static int count;
test t3;
Public:
t3.setcode();
Void setcode(void)
test::showcount();
{ code=++count;}
t1.showcode();
Void showcode(void)
t2.showcode();
{ cout<<“object no.:”<<code;}
t3.showcode(); Output
Static void showcount(void)
Return 0; Count:2
{ cout<<“count:”<<count; }
} Count :3
};
Int test::count; Object number:1
Object number:2
Object number:3
Constructors
• A constructor is a ‘special’ member function
whose task is to initialize the objects of its
class.
• It is special because its name is the same as the
class name.
• Constructor is invoked whenever an object of
its associated class is created.
• It is called constructor because it constructs the
values of data members of the class.
Constructors
• A constructor function is a special member
function that is a member of a class and has
the same name as that class, used to create,
and initialize objects of the class.
• Constructor function do not have return type.
• Should be declared in public section.
• Invoked automatically when objects are
created
Constructors
Syntax: Example:
class class_name class student
{ { int st_id;
public: public:
class_name();
student()
};
{
st_id=0;
}
};
Constructors
• How to call this special function…?
class student
{
int main() int st_id;
{ public:
student st; student()
………… {
………… st_id=0;
}; }
};
Constructor can be defined inside the class declaration or
outside the class declaration
<class-name>(list-of-parameters)
{
//constructor definition
}
<class-name>: :<class-name>(list-of-parameters)
{
//constructor definition
}
Characteristics of Constructors
• They should be declared in the public section.
• They are invoked automatically when the objects are
created.
• They do not have return types, not even void .
• They cannot be inherited, though a derived class can
call the base class constructor.
• Like c++ functions, they can have default arguments.
• Constructors cannot be virtual.
• We cannot refer to their addresses.
• They make implicit calls to the operators new and
delete when memory allocation is required.
// Example: defining the constructor within the class
#include<iostream>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student()
{
cout<<"Enter the RollNo:";
cin>>rno;
cout<<"Enter the Name:";
cin>>name;
cout<<"Enter the Fee:";
cin>>fee;
}
void display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}
};
int main()
{
student s; //constructor gets called automatically when we
//create the object of the class
s.display();
return 0;
}
// Example: defining the constructor outside the class
#include<iostream>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student();
void display();
};
student::student()
{
cout<<"Enter the RollNo:";
cin>>rno;
cout<<"Enter the Name:";
cin>>name;
cout<<"Enter the Fee:";
cin>>fee;
}
void student::display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}
int main()
{
student s;
s.display();
return 0;
}
• Characteristics of the constructor:
• The name of the constructor is the same as its class name.
• Constructors are mostly declared in the public section of
the class though it can be declared in the private section of
the class.
• Constructors do not return values; hence they do not have
a return type.
• A constructor gets called automatically when we create the
object of the class.
• Constructors can be overloaded.
• Constructor can not be declared virtual.
• Constructor cannot be inherited.
• Addresses of Constructor cannot be referred.
• Constructor make implicit calls to new and delete operators
Types of Constructors
• Constructors with default argument : no
arguments
• Parameterized constructors : constructor that
can take arguments
• Copy constructors : accept a reference to its
own class as a parameter (object as a
argument)
• Dynamic Constructor : allocation of memory to
object at the time of their construction
Parameterized constructor
• Calling parameterized constructors :
1) By calling the constructor explicitly
e.g. demo d=demo(1,2);
2) By calling the constructor implicitly
e.g. demo d(1,2);
Parameterized Constructors
class Addition
{
meters
int num1; C o n st ru ctor wi t h
f
p
u
a
n
ra
ction!
o a
z it’s als
int num2; B’ Co
int res;
public:
Addition(int a, int b); // constructor
void add( );
void print(); Constructor that can take
}; arguments is called
parameterized constructor.
Overloaded Constructors
class Addition
{
int num1,num2,res;
n stru ctor with
float num3, num4, f_res; Overloaded CBo’Coz they are
ers
paramet ions!
public: also fun
ct
int res;
public:
Addition(); // constructor
void add( );
void print();
};
/ CPP program to illustrate the concept of Constructors
#include <iostream>
using namespace std;
class construct {
public:
int a, b;
// Default Constructor
construct()
{
a = 10;
b = 20;
}
};
int main()
{
Construct c; // Default constructor called automatically when the object is created
cout << "a: " << c.a << endl << "b: " << c.b;
return 1;
}
Dynamic Constructors
Used to allocate memory at the time of object
creation
class Sum_Array
{
int *p;
public:
Sum_Array(int sz) // constructor
{
p=new int[sz];
}
};
Destructors
• A destructor function is a special function that
is a member of a class and has the same
name as that class used to destroy the objects
that have been created by a constructor.
• Must be declared in public section.
• Destructor do not have arguments & return
type.
NOTE:
A class can have ONLY ONE destructor
Destructors
Synatax: Example:
class class_name class student
{ {
public: public:
~student()
~class_name();
{
}; cout<<“Destructor”;
}
};
Local Classes
• A class defined within a function is called Local
Class.
void fun()
Syntax: {
void function() class myclass {
{ int i;
class class_name public:
{ void put_i(int n) { i=n; }
// class definition int get_i() { return i; }
} obj; } ob;
//function body ob.put_i(10);
} cout << ob.get_i();
}
Multiple Classes
Synatax: Example: Example:
class class_name1 class test class student
{ { int st_id;
{ public: test m;
//class definition int t[3]; public:
}; }; void init_test()
{
class class_name2
m.t[0]=25;
{ m.t[1]=22;
//class definition m.t[2]=24;
}; }
};
Nested Classes
Synatax: Example:
class student
class outer_class { int st_id;
{ public:
class dob
//class definition { public:
class inner_class int dd,mm,yy;
}dt;
{ void read()
//class definition {
dt.dd=25;
}; dt.mm=2;
dt.yy=1988;}
};
};
Friend Functions
• To make an outside function “friendly” to a
class, declare the function as a friend of the
class.
• Friend function is a non-member function which
can access the private members of a class
st
ptr 2FCD54
Pointers to Objects
• Pointers can be defined to hold the address of an
object, which is created statically or dynamically
Example:
stp st_name;
stp read_data ( );
The this Pointer
• The this pointer points to the object that
invoked the function