Object-Oriented Programming (OOP) : Dr. G. Prabu Kanna Associate Professor / Ce
Object-Oriented Programming (OOP) : Dr. G. Prabu Kanna Associate Professor / Ce
Object-Oriented Programming (OOP) : Dr. G. Prabu Kanna Associate Professor / Ce
Object
• This is the basic unit of object-oriented programming.
That is both data and function that operate on data are
bundled as a unit called an object.
Class
• When you define a class, you define a blueprint for an
object. This doesn't actually define any data, but it does
define what the class name means, that is, what an object
of the class will consist of and what operations can be
performed on such an object.
Object-oriented programming (OOP)
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
Object-oriented programming (OOP)
• Abstraction
• It refers to, providing only essential information to the outside world and
hiding their background details.
• For example, a web server hides how it processes data it receives, the end
user just hits the endpoints and gets the data back.
Object-oriented programming (OOP)
Encapsulation
Inheritance
For example,
if we have a class Vehicle that has properties like Color, Price, etc,
we can create 2 classes like Bike and Car from it that have those 2
properties and additional properties that are specialized for them like a car has
number of Windows while a bike cannot.
Same is applicable to methods.
Object-oriented programming (OOP)
OOP has four basic concepts on which it is totally based.
Polymorphism
On the basis of nature of developing the code both languages have different
approaches on basis of which both are differentiate from each other.
Benefits of OOP
It is easy to model a real system as real objects are represented by
programming objects in OOP. The objects are processed by their member
data and functions. It is easy to analyze the user requirements.
With the help of inheritance, we can reuse the existing class to derive a new
class such that the redundant code is eliminated and the use of existing class
is extended. This saves time and cost of program.
In OOP, data can be made private to a class such that only member functions
of the class can access the data. This principle of data hiding helps the
programmer to build a secure program that can not be invaded by code in
other part of the program.
Benefits of OOP
With the help of polymorphism, the same function or same operator can be
used for different purposes. This helps to manage software complexity easily.
#include<conio.h>
void main() {
clrscr();
getch();
}
To write the first C++ program, open the C++ console
and write the following code:
#include<iostream.h> includes the standard input output library functions. It
provides cin and cout methods for reading from input and writing to output
respectively.
#include <conio.h> includes the console input output library functions. The getch()
function is defined in conio.h file.
void main() The main() function is the entry point of every program in C++ language.
The void keyword specifies that it returns no value.
cout << "Welcome to C++ Programming." is used to print the data "Welcome to C++
Programming." on the console.
getch() The getch() function asks for a single character. Until you press any key, it
blocks the screen.
How to compile and run the C++ program
There are 2 ways to compile and run the C++ program, by menu and by shortcut.
By menu
Now click on the compile menu then compile sub menu to compile the c++
program.
Then click on the run menu then run sub menu to run the c++ program.
By shortcut
Or, press ctrl+f9 keys compile and run the program directly.
C++ Variable
A variable is a name of memory location. It is used to store data. Its value can be
changed and it can be reused many times.
type variable_list;
The example of declaring variable is given below:
int x;
float y;
char z;
Here, x, y, z are variables and int, float, char are data types.
Rules for defining variables
A variable can have alphabets, digits and underscore.
A variable name can start with alphabet and underscore only. It can't start with digit.
A variable name must not be any reserved word or keyword e.g. char, float etc.
int a;
int _ab;
int a30;
int d=3, f=5;
byte z=22;
char x=’x’;
int 4;
int x y;
int double;
C++ Data Types
• A data type specifies the type of data that a variable can store such as
integer, floating, character etc.
C++ Data Types
• There are 4 types of data types in C++ language.
• The basic data types are integer-based and floating-point based. C++
language supports both signed and unsigned literals.
• The memory size of basic data types may change according to 32 or 64 bit
operating system.
• Let's see the basic data types. It size is given according to 32 bit OS.
Basic Data Types
• Consider a situation, when we have two persons with the same name,
Zara, in the same class.
• Same situation can arise in your C++ applications. For example, you
might be writing some code that has a function called xyz() and there
is another library available which is also having same function xyz().
• Using namespace, you can define the context in which names are defined.
In essence, a namespace defines a scope
Namespaces in C++
• #include <iostream>
• using namespace std;
• int main () {
• // Calls function from first name space.
• first_space::func();
•
• // Calls function from second name space.
• second_space::func();
• return 0;
• }
• If we compile and run above code, this would produce the following result −
• Inside first_space
• Inside second_space
Namespaces in C++
The using directive
• You can also avoid prepending of namespaces with the using namespace
directive.
• This directive tells the compiler that the subsequent code is making use of
names in the specified namespace. The namespace is thus implied for the
following code −
Namespaces in C++
#include <iostream>
using namespace std;
return 0;
}
If we compile and run above code, this would produce the following result −
Inside first_space
Identifiers in C++
• They are fixed values in a program. There can be any types of constants like
integer, float, octal, hexadecimal, character constants, etc.
• Every constant has some range. The integers that are too big to fit into an int
will be taken as long.
• Now there are various ranges that differ from unsigned to signed bits.
• Under the signed bit, the range of an int varies from -128 to +127, and under
the unsigned bit, int varies from 0 to 255.
Constants in C++
Constants in C++
• Defining Constants:
• In C++ program we can define constants in two ways as shown below:
• Literals: The values assigned to each constant variables are referred to as the
literals.
• For eg, “const int = 5;“, is a constant expression and the value 5 is referred to as
constant integer literal.
• interger literals
• floating point literals
• boolean literals
• character literals
• String literals
Constants in C++
• Let us now learn about above two ways in details:
C++ Enums can be thought of as classes that have fixed set of constants.
C++ Enumeration
Points to remember for C++ Enum
• enum improves type safety
• enum may implement many interfaces but cannot extend any class
because it internally extends Enum class
C++ Enumeration
C++ Enumeration Example
• #include <iostream>
• using namespace std;
• enum week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
• int main()
• {
• week day;
• day = Friday;
• cout << "Day: " << day+1<<endl;
• return 0;
• }
Output:
• Day: 5
C++ Enumeration
C++ Enumeration Example
• #include <iostream>
• using namespace std;
• enum colors{red=5, black};
• enum suit{heart, diamond=8, spade=3, club};
• int main() {
• cout <<"The value of enum color : "<<red<<","<<black;
• cout <<"\nThe default value of enum suit :
"<<heart<<","<<diamond<<","<<spade<<","<<club;
• return 0;
• }
Output:
Operators are symbols that perform operations on variables and values. For
example, + is an operator used for addition, while - is an operator used for
subtraction.
Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators
Bitwise Operators
Other Operators
C++ Operators
Operators are symbols that perform operations on variables and values. For
example, + is an operator used for addition, while - is an operator used for
subtraction.
Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators
Bitwise Operators
Other Operators
C++ Operators
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Operation (Remainder
after division)
Example 1: Arithmetic Operators
#include <iostream>
using namespace std;
int main() {
int a, b;
a = 7;
b = 2;
return 0;
}
Example 1: Arithmetic Operators
For example,
int num = 5;
// increment operator
++num; // 6
Example 3: Assignment Operators
#include <iostream>
using namespace std;
int main() {
int a, b;
// 2 is assigned to a
a = 2;
// 7 is assigned to b
b = 7;
int main() {
int a, b;
a = 3;
b = 5;
bool result;
Generally takes place when in an expression more than one data type is present. In
such condition type conversion (type promotion) takes place to avoid lose of data.
All the data types of the variables are upgraded to the data type of the variable
with largest data type.
• bool -> char -> short int -> int ->
• int main()
• {
• int x = 10; // integer x
• char y = 'a'; // character c
This process is also called type casting and it is user-defined. Here the user
can typecast the result to make it of a particular data type.
In C++, it can be done by two ways:
int main()
{
double x = 1.2;
return 0;
}
Output:
Sum = 2
C++ Overloading (Function and Operator)
If we create two or more members having the same name but different in
number or type of parameter, it is known as C++ overloading. In C++, we can
overload:
• methods,
• constructors, and
• indexed properties
• #include <iostream>
• using namespace std;
• class Cal {
• public:
• static int add(int a,int b){
• return a + b;
• }
• static int add(int a, int b, int c)
• {
• return a + b + c;
• }
• };
• int main(void) {
• Cal C; // class object declaration.
• cout<<C.add(10, 20)<<endl;
• cout<<C.add(12, 20, 23); Output:
• return 0;
• }
30
55
Program of function overloading with different types of
arguments.
• #include<iostream>
• using namespace std;
• int mul(int,int);
• float mul(float,int);
•
•
• int mul(int a,int b)
• {
• return a*b;
• }
• float mul(double x, int y)
• {
• return x*y;
• }
• int main()
• {
• int r1 = mul(6,7);
• float r2 = mul(0.2,3);
• std::cout << "r1 is : " <<r1<< std::endl;
• std::cout <<"r2 is : " <<r2<< std::endl; Output:
• return 0;
• }
r1 is : 42
r2 is : 0.6
Default arguments in C++
• #include <iostream>
• using namespace std;
• int sum(int a, int b=10, int c=20);
• int main(){
• /* In this case a value is passed as 1 and b and c values are taken from default arguments.*/
• cout<<sum(1)<<endl;
• /* In this case a value is passed as 1 and b value as 2, value of c values is taken from default arguments.
*/
• cout<<sum(1, 2)<<endl;
• /* In this case all the three values are passed during function call, hence no default arguments have been
used. */
• cout<<sum(1, 2, 3)<<endl;
• return 0;
• }
• int sum(int a, int b, int c){
• int z; Output:
• z = a+b+c;
• return z;
31
• }
23
6
Return by reference in C++
• For that purpose, C++ provides control structures that serve to specify what
has to be done by our program, when and under which circumstances.
• if (condition) statement
if (x == 100)
cout << "x is 100";
Conditional structure: if and else
• if (x == 100)
• {
• cout << "x is ";
• cout << x;
• }
Conditional structure: if and else
For example:
• if (x == 100)
• cout << "x is 100";
• else
• cout << "x is not 100";
Conditional structure: if and else
• The following example shows its use telling if the value currently stored in x
is positive, negative or none of them (i.e. zero):
• if (x > 0)
• cout << "x is positive";
• else if (x < 0)
• cout << "x is negative";
• else
• cout << "x is 0";
Iteration structures (loops)
• The while loop Its format is: while (expression) statement and its
functionality is simply to repeat statement while the condition set in
expression is true.
Iteration structures (loops)
• while (n>0) {
• cout << n << ", ";
• --n; output:
• } Enter the starting number > 8
• cout << "FIRE!\n"; 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
• return 0;
Iteration structures (loops)
The do-while loop
• // number echoer
• #include <iostream>
• using namespace std;
• int main ()
• {
• unsigned long n;
• do {
• cout << "Enter number (0 to end): ";
• cin >> n;
• cout << "You entered: " << n<< "\n";
• } while (n != 0);
• return 0;
Output:
• } Enter number (0 to end): 12345
You entered: 12345
Enter number (0 to end): 160277
You entered: 160277
The for loop
• You should use this feature with caution since its execution causes an unconditional
jump ignoring any type of nesting limitations. The destination point is identified by a
label, which is then used as an argument for the goto statement. A label is made of a
valid identifier followed by a colon (:).
• // goto loop example
• #include <iostream>
• using namespace std;
• int main ()
• {
• int n=10;
• loop:
• cout << n << ", ";
• n--;
• if (n>0) goto loop; Output:
• cout << "FIRE!\n"; 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
• return 0; FIRE!
Jump statements.
The exit function
• exit is a function defined in the cstdlib library. The purpose of exit is to terminate the
current program with a specific exit code. Its prototype is:
• The exitcode is used by some operating systems and may be used by calling
programs. By convention, an exit code of 0 means that the program finished
normally and any other value means that some error or unexpected results
happened.
Jump statements.
The selective structure: switch
• The syntax of the switch statement is a bit peculiar. Its objective is to check several
possible constant values for an expression
• switch (x) {
• case 1:
• cout << "x is 1";
• break;
• case 2:
• cout << "x is 2";
• break;
• default:
• cout << "value of x unknown";
• }
Return by Reference
• In C++ Programming, not only can you pass values by reference to a function but you can also return a value by reference.
• #include <iostream>
• using namespace std;
• // Global variable
• int num;
• // Function declaration
• int& test();
• int main()
• {
• test() = 5;
• In call by value, value being passed to the function is locally stored by the function
parameter in stack memory location. If you change the value of function parameter,
it is changed for the current function only. It will not change the value of variable
inside the caller method such as main().
understand the concept of call by value in C++ language
by the example given below
• #include <iostream>
• using namespace std;
• void change(int data);
• int main()
• {
• int data = 3;
• change(data);
• cout << "Value of the data is: " << data<< endl;
• return 0;
• }
• void change(int data)
• {
• data = 5; Output:
• }
Value of the data is: 3
Call by reference in C++
• In call by reference, original value is modified because we pass reference (address).
• Here, address of the value is passed in the function, so actual and formal arguments
share the same address space. Hence, value changed inside the function, is reflected
inside as well as outside the function.
understand the concept of call by reference in C++
language by the example given below:
• #include<iostream>
• using namespace std;
• void swap(int *x, int *y)
• {
• int swap;
• swap=*x;
• *x=*y;
• *y=swap;
• }
• int main()
• {
• int x=500, y=100;
• swap(&x, &y); // passing value to function
• cout<<"Value of x is: "<<x<<endl;
• Output:
cout<<"Value of y is: "<<y<<endl;
• return 0; Value of x is: 100
• } Value of y is: 500
Difference between call by value and call by reference
in C++
No. Call by value Call by reference
1 A copy of value is passed to the function An address of value is passed to the
function
2 Changes made inside the function is not Changes made inside the function is
reflected on other functions reflected outside the function also
3 Actual and formal arguments will be Actual and formal arguments will be
created in different memory location created in same memory location