Oodp Unit-1
Oodp Unit-1
AND PROGRAMMING
Unit-1 - Introduction to OOPS
Dr.M.Sivakumar, AP/NWC 1
Course Outcomes (CO)
At the end of this course, learners will be able to:
• CO-1: Create programs using object-oriented approach and
design methodologies
• CO-2: Construct programs using method overloading and
operator overloading
• CO-3: Create programs using inline, friend and virtual
functions, construct programs using standard templates
• CO-4: Construct programs using exceptional handling and
collections
• CO-5: Create Models of the system using UML Diagrams
Dr.M.Sivakumar, AP/NWC 2
Unit-1 - Introduction to OOPS
1. Object-Oriented Programming - Features of C++
2. I/O Operations, Data Types, Variables-Static, Constants,
Pointers
3. Type Conversions - Conditional and looping statements
4. Arrays - C++ 11 features
5. Class and Objects, Abstraction and Encapsulation,
6. Access Specifiers, Methods
7. UML Diagrams Introduction - Use Case Diagram, Class
Diagram.
8. Practice questions from elab
9. Quiz/Puzzles/Review Questions
Dr.M.Sivakumar, AP/NWC 3
Introduction to Object-Oriented Programming, Features of C++
SESSION-01
Dr.M.Sivakumar, AP/NWC 4
OBJECT-ORIENTED PROGRAMMING
Dr.M.Sivakumar, AP/NWC 5
Programming Languages
• Programming a computer involves writing instructions that
enable a computer to carry out a single task or a group of tasks
• Writing these sets of instructions, which are known as programs
or software, requires using a computer programming language
and resolving any errors in the instructions so that the programs
work correctly
• Programs are also frequently called application programs
• Simply applications, because you apply them to a task such as
preparing payroll checks, creating inventory reports, or—as in
the case of game programs—even entertaining someone
Dr.M.Sivakumar, AP/NWC 6
Programming Languages
• learning a computer programming language requires learning
both vocabulary and syntax.
• The rules of any language make up its syntax.
• When you write programs, you write program statements that
are instructions that are similar to English-language sentences.
Dr.M.Sivakumar, AP/NWC 7
Types of Programming Languages
• Machine level Language
• Assembly level Language
• High level Language
– Procedure oriented programming(POP) language
– Object oriented programming(OOP) language.
Dr.M.Sivakumar, AP/NWC 8
Procedure Oriented Programming Language
• Drawbacks
– Global data access
– It does not model real word problem very well
– No data hiding
Dr.M.Sivakumar, AP/NWC 9
Characteristics of procedure oriented
programming
• Emphasis is on doing things(algorithm)
• Large programs are divided into smaller programs
known as functions
• Most of the functions share global data
• Data move openly around the system from function to
function
• Function transforms data from one form to another
• Employs top-down approach in program design
Dr.M.Sivakumar, AP/NWC 10
Object Oriented Programming
• Object oriented programming as an
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
Dr.M.Sivakumar, AP/NWC 11
Object Oriented Programming
Dr.M.Sivakumar, AP/NWC 12
Object Oriented Programming
Dr.M.Sivakumar, AP/NWC 13
Object Oriented Programming
• Combine data and functions into object.
(Member Data & Member Functions)
• Member functions are also called methods.
• Member data are hidden within member
functions.
• Data Encapsulation & Data Hiding.
• Objects interact by sending messages to
each other.
Dr.M.Sivakumar, AP/NWC 14
Object Oriented Programming
Vs Procedural Oriented Programming
Procedure Oriented Programming Object Oriented Programming
program is divided into small parts program is divided into parts called objects.
called functions
Importance is not given to data but to Importance is given to the data rather than
functions as well as sequence of procedures or functions because it works as a real
actions to be done. world.
follows Top Down approach OOP follows Bottom Up approach.
It does not have any access specifier OOP has access specifiers named
Public, Private, Protected, etc
Data can move freely from objects can move and communicate with
function to function in the system each other through member functions.
It does not have any proper way for hiding data so OOP provides Data Hiding so provides more
it is less secure security
Overloading is not possible In OOP, overloading is possible in the form of
Function Overloading and Operator
Overloading.
Dr.M.Sivakumar, AP/NWC 15
Basic concepts of OOPS
1. Objects
2. Classes
3. Data abstraction and encapsulation
4. Inheritance
5. Polymorphism
6. Dynamic binding
7. Message passing
Dr.M.Sivakumar, AP/NWC 16
Objects
• Software objects model real-world objects or abstract
concepts.
dog, bicycle, queue
• Real-world objects have states and behaviors.
Dogs' states: name, color, breed, hungry
Dogs' behaviors: barking, fetching
• 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.
Dr.M.Sivakumar, AP/NWC 17
Class
• A class is a blueprint or prototype defining the variables
and methods common to all objects of a certain kind.
Dr.M.Sivakumar, AP/NWC 18
Class and Objects
Dr.M.Sivakumar, AP/NWC 19
Class and Objects
Dr.M.Sivakumar, AP/NWC 20
Class and Objects
Dr.M.Sivakumar, AP/NWC 21
Data abstraction and encapsulation
• It is a mechanism that binds together code and the
data it manipulates, and keeps both safe from
outside interference and misuse
Dr.M.Sivakumar, AP/NWC 22
Data abstraction and encapsulation
Dr.M.Sivakumar, AP/NWC 23
Data abstraction and encapsulation
• Encapsulation is as a protective wrapper that prevents the code and
data from being arbitrarily accessed by other code defined outside
the wrapper
• Access to the code and data inside the wrapper is tightly controlled
through a well-defined interface
Dr.M.Sivakumar, AP/NWC 24
Inheritance
• Inheritance is the process by which one object acquires the
properties of another object
Dr.M.Sivakumar, AP/NWC 25
Inheritance
Dr.M.Sivakumar, AP/NWC 26
Inheritance
Dr.M.Sivakumar, AP/NWC 27
Polymorphism
• Polymorphism (from Greek, meaning “many forms”) is a feature that
allows one interface to be used for a general class of actions
• The specific action is determined by the exact nature of the situation
Dr.M.Sivakumar, AP/NWC 28
Polymorphism
Dr.M.Sivakumar, AP/NWC 29
Dynamic binding
Dr.M.Sivakumar, AP/NWC 30
Message Passing
Dr.M.Sivakumar, AP/NWC 32
Applications of Object Oriented Programming
• Client-Server Systems
• Real-Time System
• Object-Oriented Databases
• Simulation and modelling
• AI and expert systems
• Neural networks and parallel programming
Dr.M.Sivakumar, AP/NWC 33
Dr.M.Sivakumar, AP/NWC 34
Introduction to C++
• C++ is a general-purpose programming language that was
developed as an extension of the C programming language with
object-oriented programming features
• C++ was invented by Bjarne Stroustrup in 1979, at Bell
Laboratories in Murray Hill, New Jersey
• C++ is derived from the C language
• C++ provides a combination of low-level features for systems
programming and high-level features for application
development.
• C++ is also the language from which both Java and C# are
derived
Dr.M.Sivakumar, AP/NWC 35
Sample C++ Program
Dr.M.Sivakumar, AP/NWC 36
Features of C++
Dr.M.Sivakumar, AP/NWC 37
Difference between C and C++
C C++
Memory management is typically done manually operators like new and delete for dynamic
using functions like malloc and free memory allocation.
Does not have a standard template library Includes the Standard Template Library (STL)
SESSION-02
Dr.M.Sivakumar, AP/NWC 39
I/O OPERATIONS, DATA TYPES,
VARIABLES-STATIC, CONSTANTS
Dr.M.Sivakumar, AP/NWC 40
I/O Operations
• C++ I/O operation occurs in streams, which involve transfer of
information into byte
• It’s a sequences of bytes
• Stream involved in two ways
• It is the source as well as the destination of data
• C++ programs input data and output data from a stream.
• Streams are related with a physical device such as the monitor or
with a file stored on the secondary memory.
• In a text stream, the sequence of characters is divided into lines,
with each line being terminated.
• With a new-line character (\n) . On the other hand, a binary stream
contains data values using their memory representation.
Dr.M.Sivakumar, AP/NWC 41
I/O Operations
Stream in C
Dr.M.Sivakumar, AP/NWC 42
Cascading of Input or Output Operators
• << operator –It can use multiple times in the same line.
• Its called Cascading
• Cout ,Cin can cascaded
• For example
• cout<<“\n Enter the Marks”;
• cin>> ComputerNetworks>>OODP;
Dr.M.Sivakumar, AP/NWC 43
Reading and Writing Characters and Strings
• char marks;
• cin.get(marks);//The value for marks is read
• OR
• marks=cin.get();//A character is read and assigned to marks
• string name;
• Cin>>name;
• string empname;
• cin.getline(empname,20);
• Cout<<“\n Welcome ,”<<empname;
Dr.M.Sivakumar, AP/NWC 44
Formatted Input and
Output Operations Formatted I/O
Dr.M.Sivakumar, AP/NWC 45
Example
#include<iostream.h>
#define PI 3.14159
main()
{
cout.precision(3);
cout.width(10);
cout.fill(‘*’);
cout<<PI;
}
Output
*****3.142
Dr.M.Sivakumar, AP/NWC 46
Formatting with flags
• The setf() is a member function of the ios class that is used to set
flags for formatting output.
• Syntax:
cout.setf(flag, bit-field)
• Here, flag defined in the ios class specifies how the output should
be formatted
• bit-field is a constant (defined in ios ) that identifies the group to
which the formatting flag belongs to.
• There are two types of setf()—one that takes both flag and
bit-fields and the other that takes only the flag .
Dr.M.Sivakumar, AP/NWC 47
Formatting with flags
Dr.M.Sivakumar, AP/NWC 48
Formatting Output Using Manipulators
Dr.M.Sivakumar, AP/NWC 49
Data Types in C++
Dr.M.Sivakumar, AP/NWC 50
Variables
A variable is the content of a memory location that stores a certain value. A variable is identified or
denoted by a variable name. The variable name is a sequence of one or more letters, digits or
underscore, for example: character_
Rules for defining variable name:
❖ A variable name can have one or more letters or digits or underscore for example character_.
❖ White space, punctuation symbols or other characters are not permitted to denote variable
name.
❖ A variable name must begin with a letter.
❖ Variable names cannot be keywords or any reserved words of the C++ programming language.
❖ Data C++ is a case-sensitive language. Variable names written in capital letters differ from
variable names with the same name but written in small letters.
Dr.M.Sivakumar, AP/NWC 52
CONSTANTS
• Constants are identifiers whose value does not change. While variables can
change their value at any time, constants can never change their value.
• Constants are used to define fixed values such as Pi or the charge on an
electron so that their value does not get changed in the program even by
mistake.
• A constant is an explicit data value specified by the programmer.
• The value of the constant is known to the compiler at the compile time.
Dr.M.Sivakumar, AP/NWC 53
Declaring Constants
• Rule 1 Constant names are usually written in capital letters to visually distinguish them
from other variable names which are normally written in lower case characters.
• Rule 2 No blank spaces are permitted in between the # symbol and define keyword.
• Rule 3 Blank space must be used between #define and constant name and between
constant name and constant value.
• Rule 4 #define is a preprocessor compiler directive and not a statement. Therefore, it does
not end with a semi-colon.
Dr.M.Sivakumar, AP/NWC 54
Operators
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
Dr.M.Sivakumar, AP/NWC 55
Arithmetic Operators
Operator Description Example
Dr.M.Sivakumar, AP/NWC 56
Relational Operators
Operator Description Example
Checks if the values of two operands are equal or not, if yes then condition
== (A == B) is not true.
becomes true.
Checks if the values of two operands are equal or not, if values are not equal
!= (A != B) is true.
then condition becomes true.
Checks if the value of left operand is greater than the value of right operand,
> (A > B) is not true.
if yes then condition becomes true.
Checks if the value of left operand is less than the value of right operand, if
< (A < B) is true.
yes then condition becomes true.
Checks if the value of left operand is greater than or equal to the value of
>= (A >= B) is not true.
right operand, if yes then condition becomes true.
Checks if the value of left operand is less than or equal to the value of right
<= (A <= B) is true.
operand, if yes then condition becomes true.
Dr.M.Sivakumar, AP/NWC 57
Logical Operators
Operator Description Example
Called Logical NOT Operator. Use to reverses the logical state of its
! operand. If a condition is true, then Logical NOT operator will make !(A && B) is true.
false.
Dr.M.Sivakumar, AP/NWC 58
Bitwise Operators
Operator Description Example
Binary AND Operator copies a bit to the result if it exists in (A & B) will give 12 which is 0000
&
both operands. 1100
(A | B) will give 61 which is 0011
| Binary OR Operator copies a bit if it exists in either operand.
1101
Binary XOR Operator copies the bit if it is set in one operand (A ^ B) will give 49 which is 0011
^
but not both. 0001
Binary Left Shift Operator. The left operands value is moved left A << 2 will give 240 which is 1111
<<
by the number of bits specified by the right operand. 0000
Simple assignment operator, Assigns values from right side C = A + B will assign value of A + B
=
operands to left side operand. into C
Add AND assignment operator, It adds right operand to the left
+= C += A is equivalent to C = C + A
operand and assign the result to left operand.
Dr.M.Sivakumar, AP/NWC 60
Misc Operators
Operator Description Example
Cast Casting operators convert one data type to another. int(2.2000) would return 2.
Dr.M.Sivakumar, AP/NWC 61
Operators Precedence in C++
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right
Dr.M.Sivakumar, AP/NWC 62
Special Operators
Scope resolution operator
In C, the global version of a variable cannot be accessed from within the inner block. C++ resolves this problem by using scope
1
resolution operator (::), because this operator allows access to the global version of a variable.
new Operator
2 The new operator denotes a request for memory allocation on the Heap. If sufficient memory is available, new operator initializes the
memory and returns the address of the newly allocated and initialized memory to the pointer variable.
delete Operator
3 Since it is programmer’s responsibility to deallocate dynamically allocated memory, programmers are provided delete operator by C++
.
language
Member Operator
4 C++ permits us to define a class containing various types of data & functions as members. To access a member using a pointer in the
object & a pointer to the member.
Dr.M.Sivakumar, AP/NWC 63
Pointers
• Pointers are symbolic representation of addresses.
• They enable programs to simulate call-by-reference as well as to create and manipulate
dynamic data structures.
• Syntax data_type *pointer_variable;
• Example
int *p,sum;
Assignment
• integer type pointer can hold the address of another int variable
• To assign the address of variable to pointer-ampersand symbol (&)
p=∑
this pointer
hold the adderss of current object
int num;
this->num=num;
Void?
• When used in the declaration of a pointer, void specifies that the pointer is
"universal." If a pointer's type is void* , the pointer can point to any variable that's not
declared with the const or volatile keyword.
Dr.M.Sivakumar, AP/NWC 64
Pointers
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
Steps:
(a) We define a pointer variable.
(b) Assign the address of a variable to a pointer.
(c) Finally access the value at the address available in the
pointer variable.
Dr.M.Sivakumar, AP/NWC 65
Real Time Example
Dr.M.Sivakumar, AP/NWC 66
How to use it
#include <iostream>
using namespace std;
int main ()
{
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl;
// print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << ip << endl;
// access the value at the address available in pointer
cout << "Value of *ip variable: ";
cout << *ip << endl;
Output:
return 0; Value of var variable: 20
} Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
Dr.M.Sivakumar, AP/NWC 67
Pointers and Arrays
#include <iostream>
using namespace std;
int main()
{
//Pointer declaration
int *p;
//Array declaration
int arr[]={1, 2, 3, 4, 5, 6};
//Assignment OUTPUT:
p = arr; 0
1
for(int i=0; i<6;i++) 2
{ 3
cout<<*p<<endl; 4
//++ moves the pointer to next int position 5
6
p++;
}
return 0;
Dr.M.Sivakumar, AP/NWC 68
}
this Pointers
• this pointer hold the address of current object
• int num;
• This->num=num;
Dr.M.Sivakumar, AP/NWC 69
#include <iostream>
this Pointers Example
using namespace std;
class Employee int main(void)
{ {
int id; //data member (also instance variable) Employee e1 =Employee(101, "Sonoo", 890000);
char name[20]; //data member(also instance variable) //creating an object of Employee
float salary; Employee e2=Employee(102, "Nakul", 59000);
public: //creating an object of Employee
e1.display(); e2.display(); return 0;
Employee(int id, string name, float salary)
}
{
this->id = id;
this->name = name;
this->salary = salary;
} Output:
void display() 101 Sonoo 890000
{ 102 Nakul 59000
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
Dr.M.Sivakumar, AP/NWC 70
Function using pointers
#include<iostream> void swap(int *a,int *b)
using namespace std; {
void swap(int *a ,int *b ); int c;
//Call By Reference c=*a;
int main() *a=*b;
{ *b=c;
int p,q; }
cout<<"\nEnter Two Number You Want To Swap \n";
cin>>p>>q; Output:
swap(&p,&q); Enter Two Number You Want to Swap
cout<<"\nAfter Swapping Numbers Are Given below\n\n"; 10 20
cout<<p<<" "<<q<<" \n"; After Swapping Numbers Are Given below
return 0; 20 10
}
Dr.M.Sivakumar, AP/NWC 71
MCQ
a) b is assigned to a
b) p now points to b
c) a is assigned to b
d) q now points to a
Dr.M.Sivakumar, AP/NWC 72
MCQ
a) b is assigned to a
b) p now points to b
c) a is assigned to b
d) q now points to a
Dr.M.Sivakumar, AP/NWC 73
MCQ
What is output of the following code?
#include <iostream>
using namespace std;
int main()
{
char arr[20];
int i;
for(i = 0; i < 10; i++)
*(arr + i) = 65 + i;
*(arr + i) = '\0';
cout << arr;
return(0);
}
Dr.M.Sivakumar, AP/NWC 74
MCQ
Answer: ABCDEFGHIJ
Explanation:
• Each time we are assigning 65 + i.
• In first iteration i = 0 and 65 is assigned.
• So it will print from A to J.
Dr.M.Sivakumar, AP/NWC 75
Type Conversions,
Conditional and Looping Statements
SESSION-03
Dr.M.Sivakumar, AP/NWC 76
Type Conversions
• Type conversion is the process that converts the predefined data type of
one variable into an appropriate data type.
• Type conversion can be done in two ways in C++
1. Implicit type conversion
2. Explicit type conversion
Dr.M.Sivakumar, AP/NWC 77
Implicit Type Conversions
• The type conversion that is done automatically done by the compiler
• This type of conversion is also known as automatic conversion
#include <iostream>
using namespace std;
int main ()
{
// assign the integer value
int num1 = 25;
// declare a float variable
float num2;
// convert int value into float variable using implicit conversion
num2 = num1;
cout << " The value of num1 is: " << num1 << endl;
cout << " The value of num2 is: " << num2 << endl;
return 0;
} Output:
The value of num1 is: 25
Dr.M.Sivakumar, AP/NWC The value of num2 is: 25 78
Explicit Type Conversions (or)
Type Casting
• Conversions that require user intervention to change the data type of one
variable to another
• Hence, it is also known as typecasting
Dr.M.Sivakumar, AP/NWC 79
1. Explicit conversion using the cast operator
#include <iostream>
using namespace std;
int main ()
{
float f2 = 6.7;
// use cast operator to convert data from one type to another
int x = static_cast <int> (f2);
cout << " The value of x is: " << x;
return 0;
}
Dr.M.Sivakumar, AP/NWC 80
2. Explicit conversion using the assignment operator
#include <iostream>
using namespace std;
int main ()
{
// declare a float variable
float num2;
// initialize an int variable
int num1 = 25;
Dr.M.Sivakumar, AP/NWC 81
Conditional and looping statements
• if…else
• switch
• for
• while
• do…while
• break
• continue
Dr.M.Sivakumar, AP/NWC 82
Arrays - C++ 11 features
SESSION-04
Dr.M.Sivakumar, AP/NWC 83
Arrays
• Declaring Arrays
type arrayName [ arraySize ];
• Initializing Arrays
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
balance[4] = 50.0;
Dr.M.Sivakumar, AP/NWC 85
C++ version 11 features
• Simple and User Friendly
• Object Oriented Programming
• Platform Dependent
• Structured Programming Language
• Mid-Level Programming Language
• Rich Library
• Case-Sensitive
• Dynamic Memory Allocation
• Memory Management
• Powerful and Fast
Dr.M.Sivakumar, AP/NWC 86
Class and Objects, Abstraction and
Encapsulation
SESSION-05
Dr.M.Sivakumar, AP/NWC 87
CLASS AND OBJECTS, ABSTRACTION AND
ENCAPSULATION
Dr.M.Sivakumar, AP/NWC 88
Class
• Class is a user defined data type, defined using keywork class.
• It holds its own data members and member functions,
• It can be accessed and used by creating instance of that class.
• The variables inside class definition are called as data members and
the functions are called member functions
class className
{
data members
member functions
};
Dr.M.Sivakumar, AP/NWC 89
Syntax of Class
class ClassName
{
public:
// Member variables (attributes)
dataType memberVariable1;
dataType memberVariable2;
// ...
Dr.M.Sivakumar, AP/NWC 90
Class
• Class is just a blue print, which declares and defines Example
class Room
characteristics and behavior, namely data members {
public:
and member functions respectively.
double length;
• All objects of this class will share these characteristics double breadth;
double height;
and behavior.
double calculateArea()
• Class name must start with an uppercase
{
letter(Although this is not mandatory). return length * breadth;
}
Example,
double calculateVolume()
class Student
{
return length * breadth * height;
}
Dr.M.Sivakumar, AP/NWC }; 91
Define a class
Dr.M.Sivakumar, AP/NWC 92
Data Member
Data members Can be of any type, built-in or user-defined.
This may be,
• non-static data member
Each class object has its own copy
Dr.M.Sivakumar, AP/NWC 93
Static Data Member
• Static data member is declared using the static keyword.
• There is only one copy of the static data member in the class. All the objects share
the static data member.
• The static data member is always initialized to zero when the first class object is
created.
Syntax:
static data_type datamember_name;
Here
static is the keyword.
data_type – int , float etc…
datamember_name – user defined
Dr.M.Sivakumar, AP/NWC 94
Static Data Member
#include <iostream>
using namespace std; int Account::count=0;
class Account int main(void)
{ {
public: Account a1 =Account(201, "Sanjay");
int accno; //data member (also instance variable) //creating an object of Account
string name; Account a2=Account(202, "Nakul");
static int count; Account a3=Account(203, "Ranjana");
Account(int accno, string name) // Constructor Function a1.display();
{ a2.display();
this->accno = accno; a3.display();
this->name = name; cout<<"Total Objects are: "<<Account::count;
count++; return 0;
} }
void display()
{
cout<<accno<<" "<<name<<endl; Output:
} 201 Sanjay
}; 202 Nakul
203 Ranjana
Total Objects are: 3
Dr.M.Sivakumar, AP/NWC 95
Member Functions
• Used to
– access the values of the data members (accessor)
– perform operations on the data members (implementor)
• Are declared inside the class body
• Their definition can be placed
– inside the class body, or
– outside the class body
• Can access both public and private members of the class
• Can be referred to using dot or arrow member access operator
Dr.M.Sivakumar, AP/NWC 96
Member Functions
keyword Class Name
}
Dr.M.Sivakumar, AP/NWC 98
const member function
#include<iostream>
using namespace std;
int main()
class sample
{ {
private: const sample s(20);
int val; sample s1(2);
public:
cout << "The value using object d : " << s.getValue();
sample(int x = 0)
{ cout << "\nThe value using object d1 : " <<
val = x; s1.getValue();
}
return 0;
int getValue() const
{ }
return val;
}
};
Dr.M.Sivakumar, AP/NWC 99
Access Specifiers, Methods
SESSION-06
•Protected members
can be accessed from
Protected within the class itself,
from derived classes
and from friend
function
Example: public
#include<iostream>
using namespace std; void student::display()
class student {
{ cout<<"Name:"<<name<<endl;
public: cout<<"Age:"<<age;
char name[20]; }
int age;
void display();
};
int main()
Output:
{
Enter name:raja
student s1;
Enter age:20
cout<<"Enter name:";
Name:raja
cin>>s1.name;
Age:20
cout<<"Enter age:";
cin>>s1.age;
s1.display();
return 0;
}
Example: private
#include<iostream> void student::getdata()
using namespace std; {
class student cout<<"Enter name:";
{ cin>>name;
private: cout<<"Enter age:";
char name[20]; cin>>age;
int age; }
public: void student::display()
void getdata(); {
void display(); cout<<"Name:"<<name<<endl;
}; cout<<"Age:"<<age;
int main() }
{
student s1;
//cin>>s1.name; Output:
//cin>>s1.age; Enter name:raja
s1.getdata(); Enter age:21
s1.display(); Name:raja
return 0; Age:21
}
Example: protected
#include<iostream>
using namespace std; void student::getdata()
class person {
{ cout<<"Enter name:";
protected: cin>>name;
char name[20]; cout<<"Enter age:";
int age; cin>>age;
}; }
class student: public person void student::display()
{ {
public: cout<<"Name:"<<name<<endl;
void getdata(); cout<<"Age:"<<age;
void display(); }
};
int main() Output:
{ Enter name:raja
student s1; Enter age:22
s1.getdata(); Name:raja
s1.display(); Age:22
return 0;
}
Syntax of Declaring Access Specifiers in C++
class ClassName
{
private:
// declare private members/methods here
public:
// declare public members/methods here
protected:
// declare protected members/methods here
};
Conclusion
• If any sensitive information that, when leaked or tampered with,
can cause trouble, always make sure to set the access
specifier as private.
• All other classes and functions can access public elements.
• Private elements cannot be accessed outside the class in which
they are declared.
• Private elements can be accessed outside the class in which they
are declared only when the class is a friend class or function is a
friend function of that class.
Conclusion
• Protected elements can be accessed by derived classes. They
are almost similar to the private access specifier.
• If we do not mention any access specifier for the members
inside the class, then by default, the Access Specifier in C++ for
the members will be Private.
• All functions are accessible to the friend function of the class.
SESSION-07
Dr.M.Sivakumar, AP/NWC
Class Diagram
•It is the most common diagram type for software documentation
•Class diagrams contain classes with their attributes (data members) and their
behaviours (member functions)
• A class is a rectangle divided into three parts ClassName
– Class name
– Class attributes (i.e. data members, variables) Attributes
– Class operations (i.e. methods)
Behaviours
•The relation between different classes makes up
a class diagram
Name
Account_Name
- Customer_Name
Attributes
- Balance
+addFunds( ) Operations
+withDraw( )
+transfer( )