SRM INSTITUTE OF SCIENCE & TECHNOLOGY, DELHI NCR CAMPUS, MODINAGAR 21CSC101T – OBJECT ORIENTED DESIGN AND PROGRAMMING Unit – 1 Dr. Uma Meena Associate Professor (CSE Dept)
Contents: Unit-1 : Introduction to OOPS Object-Oriented Programming - Features of C++ - I/O Operations, Data Types, Variables-Static, Constants-Pointers Type Conversions – Conditional and looping statements – Arrays C++ 11 features - Class and Objects, Abstraction and Encapsulation, Access Specifiers, UML Diagrams Introduction – Use Case Diagram - Class Diagram
Object-Oriented Programming - Features of C++ C++ is a general-purpose programming language that was developed as an enhancement of the C language to include an object-oriented paradigm. It is an imperative and compiled language. Object-Oriented Programming Machine Independent Simple High-Level Language Popular Case-sensitive Compiler Based Dynamic Memory Allocation Memory Management Multi-threading
Object-Oriented Programming: Concepts of Object-oriented programming Language: Class Objects Encapsulation Polymorphism Inheritance Abstraction
What is a Class in C++? A class is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A C++ class is like a blueprint for an object. But we cannot use the class as it is. We first have to create an object of the class to use its features. An Object is an instance of a Class. Note: When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated.
Defining Class in C++ A class is defined in C++ using the keyword class followed by the name of the class. Syntax: class ClassName { access_specifier : // Body of the class };
Example class Student { public: int var; // data member void print( ) { // member method cout << "Hello"; } };
Example:
What is an Object in C++? Syntax to Create an Object ClassName ObjectName ; Example Student obj;
2. Machine Independent Suppose we have written a piece of code that can run on Linux/Windows/Mac OSx which makes the C++ Machine Independent but the executable file of the C++ cannot run on different operating systems. 3. Simple It is a simple language in the sense that programs can be broken down into logical units and parts, has rich library support and has a variety of data types. Also, the Auto Keyword of C++ makes life easier.
4. High-Level Language: C++ is a High-Level Language 5. Popular 6. Case-sensitive 7. Compiler Based C++ is a compiler-based language. That is C++ programs used to be compiled and their executable file is used to run them. C++ is a relatively faster language than Java and Python.
8. Dynamic Memory Allocation 9. Memory Management C++ allows us to allocate the memory of a variable or an array in run time. This is known as Dynamic Memory Allocation. In C++, the memory must be de-allocated dynamically allocated memory manually after it is of no use. The allocation and deallocation of the memory can be done using the new and delete operators respectively.
Structure of C++ Program: /*_______________*/ //________________ Link Section: Header files Namespaces: its like a container for identifiers Means objects, functions, class. Or group of elements. using namespace std; Namespaces can be accessed in multiple ways: using namespace std; using std :: cout ;
std:: cout states that is cout defined in the std namespace
#include< stdio.h > int main( ){ const float PI=3.14; printf ("The value of PI is: % f",PI ); return 0; } Output: The value of PI is: 3.140000
What would happen if neither “using namespace std” nor “std::” is used for cout ?
Definition Section: It is used to declare some constants and assign them some value. Global Declaration Section: Variables and the class definitions which are going to be used in the program are declared to make them global.
C++ Program to Print Number Entered by User
Example : Swap Numbers (Using Temporary Variable)
Basic Input / Output in C++: C++ comes with libraries that provide us with many ways for performing input and output. In C++ input and output are performed in the form of a sequence of bytes or more commonly known as streams. Input Stream: If the direction of flow of bytes is from the device(for example, Keyboard) to the main memory then this process is called input. Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to device( display screen ) then this process is called output.
Header files available in C++ for Input/Output operations are: iostream: iostream stands for standard input-output stream. This header file contains definitions of objects like cin , cout , cerr , etc. iomanip : iomanip stands for input-output manipulators. The methods declared in these files are used for manipulating streams. This file contains definitions of setw , setprecision , etc. fstream : This header file mainly describes the file stream. bits/ stdc ++: This header file includes every standard library.
Standard output stream ( cout ): It display the screen, insertion operator(<<)
standard input stream ( cin ): read input from the standard input device which is usually a keyboard and use extraction operator(>>). #include <iostream> using namespace std; int main( ) { int age; cout << "Enter your age:"; cin >> age; cout << "\ nYour age is: " << age; return 0; }
C++ Data Types: Basic Data Type: int, char, float, double, etc Derived Data Type: array, pointer, etc Enumeration Data Type: enum User Defined Data Type: structure
C++ Data Types:
#include <iostream> using namespace std; int main( ) { int var = 10; cout << var; return 0; }
Character Data Type (char): The character data type is used to store a single character. #include <iostream> using namespace std; int main( ) { // Character variable char c = ‘U'; cout << c; return 0; }
Boolean Data Type (bool): Bool keyword is used to define a boolean variable. Syntax bool name; //where name is the identifier assigned to the variable. #include <iostream> using namespace std; int main( ) { // Creating a boolean variable bool isTrue = true; cout << isTrue ; return 0; }
Floating Point Data Type (float): Syntax float name; float f = 36.5; cout << f; #include <iostream> using namespace std; // Function with void return type void hello() { cout << "Hello, World!" << endl ; } int main() { hello(); return 0; } Syntax: void functionName ();
Variables in C++: Static Variable When a variable is declared as static, space for the static variable is allocated only once and the value of variable in the previous call gets carried through the next function call. Example: static int count=0; Constant Variable the variable declared as "constant", which means unchangeable and read-only Example: const int count=0; const int myNum = 15; // myNum will always be 15 myNum = 10; // error: assignment of read-only
C++ Reference Variable/ Pointers A pointer refers to a variable that holds the address of another variable. For example, a pointer of type integer can hold the address of a variable of type integer. Example of valid pointer declarations int *x; // a pointer to integer double *x; // a pointer to double float *x; // a pointer to float char * ch // a pointer to a character
#include <iostream> using namespace std; int main() { // Defining and initializing a variable int age1 = 15; // Defining a variable int age2; // Initialize the variable age2 = 99; // Displaying variable cout << age1 << endl ; cout << age2; return 0; } Example: Store Data in a Variable and Print
C++ Tokens A token is the smallest element of a program that is meaningful to the compiler. Tokens can be classified as follows: Keywords Identifiers Constants Strings Special Symbols Operators
Keywords in C++ Keywords are pre-defined or reserved words in a programming language.
C++ Type Modifiers: There are 4 type modifiers in C++. They are: signed unsigned short long We can modify the following data types with the above modifiers: int double char
C++ Operator: An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.
Ternary or Conditional Operators(?:) Expression1? Expression2: Expression3
If Statement: The if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not #include <iostream> using namespace std; int main() { int i = 10; if ( i > 15) { cout << "10 is greater than 15"; } cout << "I am Not in if"; }
if-else: The if-else statement consists of two blocks, one for false expression and one for true expression. #include <iostream> using namespace std; int main() { int i = 20; if ( i < 15) cout << " i is smaller than 15"; else cout << " i is greater than 15"; return 0; }
There are three types of loops in C++ 1. For Loop 2. While Loop 3. Do-While Loop #include <iostream> using namespace std; int main() { for(int i =1;i<=10;i++) { cout << i <<"\n"; } return 0; }
While loop #include <iostream> using namespace std; int main() { int i =1; while( i <=10) { cout << i <<"\n"; i ++; } }
Do-while loop #include <iostream> using namespace std; int main() { int i = 1; do { cout << i <<"\n"; i ++; } while ( i <= 10) ; }
Let’s name Classes and Object 54
Scope resolution operator :: Scope resolution operator (::) in C++ is used to define a function outside a class The scope resolution operator signifies the class to which belong. The class name is specified on the left-hand side of the scope resolution operator. The name of the function being defined is on the right-hand side. Example: class_name :: member_function_name(){ } 55
56 #include <iostream> using namespace std; class Game { public: void play(); // Function declaration }; // function definition outside the class void Game::play() { cout << "Function defined outside the class.\n"; } int main() { Game g; g.play (); return 0; } Function declared inside class Using scope to define function procedure outside of class Scope resolution operator ::
Access Specifier / Modifier Data hiding refers to restricting access to data members of a class. This is to prevent other functions and classes from tampering with the class data However, it is also important to make some member functions and member data accessible so that the hidden data can be manipulated indirectly. The access modifiers of C++ allows us to determine which class members are accessible to other classes and functions, and which are not. 57
public Access Modifier The public keyword is used to create public members (data and functions). The public members are accessible from any part of the program. The public elements are accessible from main(). This is because public elements are accessible from all parts of the program. The public can be accessed from within class or outside class. 58
59
60
61 #include <iostream> using namespace std; // define a class class Sample { // publielements public:c int age; void displayAge () { cout << "Age = " << age << endl ; } }; int main() { // declare a class object Sample obj1; cout << "Enter your age: "; // store input in age of the obj1 object cin >> obj1.age; // call class function obj1.displayAge(); return 0; } public Access Modifier
62 #include <iostream> using namespace std; // define a class class Sample { // public elements public: int age; void displayAge () { cout << "Age = " << age << endl ; } }; int main() { // declare a class object Sample obj1; cout << "Enter your age: "; // store input in age of the obj1 object cin >> obj1.age; // call class function obj1.displayAge(); return 0; } public Access Modifier
private Access Modifier The private keyword is used to create private members (data and functions). The private members can only be accessed from within the class. However, friend classes and friend functions can access private members. 63
64 #include <iostream> using namespace std; // define a class class Sample { // private elements/attributes private: int age; // public methods public: void displayAge (int a) { age = a; cout << "Age = " << age << endl ; } }; int main() { int ageInput ; // declare an object Sample obj1; cout << "Enter your age: "; cin >> ageInput ; // call function and pass ageInput as argument obj1.displayAge( ageInput ); return 0; } private Access Modifier
65
66
67
Protected Access Modifier The protected keyword is used to create protected members. The protected are used in inheritance. Father ------ son Base class -------derived class/child class 68
Constructor 69 A constructor gets called automatically when we create the object of the class. It is used to initialize the data members of new object generally. The constructor in C++ has the same name as class or structure. There can be two types of constructors in C++. Default constructor Parameterized constructor
Constructor 70 Constructors are mostly declared in the public section of the class though they 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.
Types of Constructor Definitions in C++ In C++, there are 2 methods by which a constructor can be declared: 1. Defining the Constructor Within the Class <class-name> (list-of-parameters) { // constructor definition } 71
2. Defining the Constructor Outside the Class <class-name> { // Declaring the constructor // Definiton will be provided outside <class-name>( ); // Defining remaining class } <class-name>: :<class-name>(list-of-parameters) { // constructor definition } 72
73
74
DEFAULT CONSTRUCTOR 75 A constructor which has no argument is known as default constructor. A default constructor is a constructor that doesn’t take any argument. It has no parameters. It is also called a zero-argument constructor. class Employee { public: Employee( ) { cout <<"Default Constructor Invoked"<< endl ; } }; Class Name is Employee Constructor given as same name as class name Employee()
76 #include <iostream> using namespace std; class Employee { public: Employee() { cout <<"Default Constructor Invoked"<< endl ; } }; int main(void) { Employee e1; Employee e2; return 0; } Class Name is Employee Constructor given as same name as class name Employee() Constructor invoked at the time of object creation DEFAULT CONSTRUCTOR
Parameterized Constructor 77 A constructor which has parameters is called parameterized constructor. It is used to provide different values to distinct objects. class Employee { public: Employee(int i , float c) { id= i ; salary=c; } }; Class Name is Employee Constructor given as same name as class name Employee()
78
79 #include <iostream> using namespace std; class Employee { public: int id; string name; float salary; Employee(int i , string n, float s) { id = i ; name = n; salary = s; } void display() { cout <<id<<" "<<name<<" "<<salary<< endl ; } }; Parameterized Constructor int main(void) { Employee e1 =Employee(101, " Sonoo ", 890000); //creating an object of Employee Employee e2=Employee(102, "Nakul", 59000); e1.display(); e2.display(); return 0; }
Destructor 80 A destructor works opposite to constructor; it destructs the objects of classes. It can be defined only once in a class. Like constructors, it is invoked automatically. A destructor is defined like constructor. It must have same name as class. But it is prefixed with a tilde sign (~). Destructor is an instance member function that is invoked automatically whenever an object is going to be destroyed. Meaning, a destructor is the last function that is going to be called before an object is destroyed.
81 #include <iostream> using namespace std; class Employee { public: Employee() { cout <<"Constructor Invoked"<< endl ; } ~Employee() { cout <<"Destructor Invoked"<< endl ; } }; int main(void) { Employee e1; //creating an object of Employee Employee e2; //creating an object of Employee return 0; } Destructor
2. Defining the Constructor Outside the Class <class-name> { // Declaring the constructor // Definiton will be provided outside <class-name>( ); // Defining remaining class } <class-name>: :<class-name>(list-of-parameters) { // constructor definition } 82
83
84
DEFAULT CONSTRUCTOR 85 A constructor which has no argument is known as default constructor. A default constructor is a constructor that doesn’t take any argument. It has no parameters. It is also called a zero-argument constructor. class Employee { public: Employee( ) { cout <<"Default Constructor Invoked"<< endl ; } }; Class Name is Employee Constructor given as same name as class name Employee()
86 #include <iostream> using namespace std; class Employee { public: Employee() { cout <<"Default Constructor Invoked"<< endl ; } }; int main(void) { Employee e1; Employee e2; return 0; } Class Name is Employee Constructor given as same name as class name Employee() Constructor invoked at the time of object creation DEFAULT CONSTRUCTOR
Parameterized Constructor 87 A constructor which has parameters is called parameterized constructor. It is used to provide different values to distinct objects. class Employee { public: Employee(int i , float c) { id= i ; salary=c; } }; Class Name is Employee Constructor given as same name as class name Employee()
88
89 #include <iostream> using namespace std; class Employee { public: int id; string name; float salary; Employee(int i , string n, float s) { id = i ; name = n; salary = s; } void display() { cout <<id<<" "<<name<<" "<<salary<< endl ; } }; Parameterized Constructor int main(void) { Employee e1 =Employee(101, " Sonoo ", 890000); //creating an object of Employee Employee e2=Employee(102, "Nakul", 59000); e1.display(); e2.display(); return 0; }
Array of Objects 90 Like array of other user-defined data types, an array of type class can also be created. The array of type class contains the objects of the class as its individual elements. Thus, an array of a class type is also known as an array of objects. An array of objects is declared in the same way as an array of any built-in data type. Syntax: class_name array_name [size] ;
91 #include <iostream> class MyClass { int x; public: void setX (int i ) { x = i ; } int getX () { return x; } }; void main() { MyClass obs [4]; int i ; for( i =0; i < 4; i ++) obs [ i ]. setX ( i ); for( i =0; i < 4; i ++) cout << " obs [" << i << "]. getX (): " << obs [ i ]. getX () << "\n"; getch (); } Array of Objects