0% found this document useful (0 votes)
89 views

Object Oriented Programming Using C++

Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
89 views

Object Oriented Programming Using C++

Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 34
MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 Computer Engineering 22316 Object Oriented Programming using C++ Procedure Oriented Programming (POP) and Object Oriented Programming (OOP) are two fundamental paradigms in software development, each with its own set of principles and usage scenarios. Procedure Oriented Programming (POP): 1, Foundations: POP, also known as procedural programming, revolves around the idea of procedure calls where you define code.as reusable functions or procedures. These procedures operate onjdata that is typically gloBalland shared. 2. Data Handling: In/POP, the emphasis is on doing operations and then managing data separately. Data is exposed to the whole program as globalyariables. 3. Functionality: Proceduresor functions are central to POP. A typical program ina procedural language like involves almain function calling other, functions to achieve its objective. 4. Examples: Languages that predominantly support POP include C, Pascal, and Fortran. 5. Main Benefits: + Simplicity: Suitable forlinear tasks. Detailed control: Offers a more handssonapproach to memory and hardware. ‘Object Oriented Programming (OOP): 1. Foundations: 008 is|centred\dtotind objects, which/atelinstanices of classes. Classes encapsulate data for the object and methods to manipulate that data 2. Data Handling: In OOP, data is bundled with the methods that operate on it, defining an ‘object’. Data is typically private to the object and can oly be modified by public methods of the object. 3. Functionality: OOP erfiphasizes splitting the program into chunks known as objects. These objects communicate with 6helanother, leading to complete functionality. 4. Examples: Languages that support OOP include Java, C++, Cit, and Python. 5. Key Principles: + Encapsulation: Restricting access to some of an object's components, allowing for the safe storage of data. + Inheritance: Creating a new class from an existing class, enabling the reuse of existing code. + Polymorphism: Allowing one interface to be used for a general class of actions. ‘+ Abstraction: Representing complex real-world problems using classes and objects, 6. Main Benefits: * Modularity: Easier maintenance and scalability by organizing code into objects. + Reusability: Leveraging inheritance and polymorphism. MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 + Flexibility: Through polymorphism and dynamic binding. Comparison: + Data vs. Functions: In POP, the focus is on procedures or functions, while in OOP, the emphasis is on grouping related functions and data together into objects. + Security: OOP offers a higher level of data security compared to POP, thanks to encapsulation which hides the data implementation details. = Reuse: OOP facilitates greater reusability of code through inheritance, allowing new objects to adopt the properties of existing ones. ‘+ Design: COP is better suited for complex and large-scale applications where multiple levels of abstraction are beneficial. POP might be more straightforward for smaller- scale applications or scripts. SEE Object-Oriented Programming (OOP) is.4 programming paradigm that focuses on the design and structuring of software using “objects.” An object represents a unique instance of a data structure that comprises both data and methods that can operate on the data. 1. Basic Concepts: + Class: A blueprint or prototype for creating instances (objects). A class defines attributes (often called fields or properties) and behaviors (referred to as methods) that its objects mighthave. + Object: Anjindividual instance of a class. It's a basic unit of OOP that represents the real-world entities. An object encompasses both data members (class attributes) and methods. ‘+ Inheritance: A mechanism wherein a new class inhefits properties and behavior (methods) from an existingi¢lassalt promotesi¢ode reusability and establishes a relationship between the parent (superclass) and child (subclass) classes. + Polymorphism: The ability of an object to take on many forms. The most common use of polymorphism is when a parent class reference is used to refer to a child class object. It allows objects of different classes to be treated as objects of a common superclass. Encapsulation: The bundling of data and methods that operate on that data into a single unit, ensuring that the object's state is hidden from the outside world. It prevents unauthorized access and modification of the data ‘Abstraction: It allows representing complex real-world problems using classes and objects, Abstraction hides the unnecessary details and only shows the essential features of an object. MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 2. Object-Oriented Languages: Several programming languages support OOP principles. Some of the prominent object- oriented languages include: + Java: A widely-used language known for its "write once, run anywhere" capability. * C++: An extension of the C language, C++ introduced the OOP features to the C language. * Python: A versatile language that supports multiple programming paradigms, including OOP. leveloped by Microsoft for its .NET framework, it's a language with strong OOP features * Ruby: Known for its elegant syntax, it's a purely object-oriented language. 3. Applications of OOP: ‘+ Software Development: OOP helps in modeling and designing complex software systems, making them more modular and easier to maintaitiand scale. + Game Development:Games often have hierarchies of.classes like characters, weapons, and enemies. OOP helps in'struetbring this hi@rarchy. ‘+ GUI Applications: Modern graphical usef interfaces are often de! principles, allowing various Ul elements to be treated as objects. + Real-time Systems: Systems like air traffie'control or medical monitoring systems can use OOP for modeling-real-World entities like airplanes or patients. + Database Systems: Object-Oriented Databases (OODB) and Object-Relational Databases (ORDB) utilize OOP Concepts to design better database systems. + Simulation and’ Modeling: OOP can represent and simulate real-world systems, like financial systems oF, any physical system, ed using OOP Object-Oriented Programming (OOP) is a programming paradigm that focuses on the design and structuring of software using "objects." An object represents a unique instance of a data structure that comprises both data and methods that can operate on the data. 1. Basic Concepts: + Class: A blueprint or prototype for creating instances (objects). A class defines attributes (often called fields or properties) and behaviors (referred to as methods) that its objects might have. + Object: An individual instance of a class. It's a basic unit of OOP that represents the real-world entities. An object encompasses both data members (class attributes) and methods. MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 + Inheritance: A mechanism wherein a new class inherits properties and behavior (methods) from an existing class. It promotes code reusability and establishes a relationship between the parent (superclass) and child (subclass) classes. * Polymorphism: The ability of an object to take on many forms. The most common use of polymorphism is when a parent class reference is used to refer to a child class object. It allows objects of different classes to be treated as objects of a common superclass. + Encapsulation: The bundling of data and methods that operate on that data into a single unit, ensuring that the object's state is hidden from the outside world. It prevents unauthorized access and modification of the data. + Abstraction: It allows representing complex real-world problems using classes and objects. Abstraction hides the unnecessary details and only shows the essential features of an object. 2. Object-Oriented Languages: Several programming languages support OOP principles. Some Of the prominent object- oriented languages includé: + Java: A widely-used language known for its write once,\run anywhere" capability. ‘= C++: An extension of the C language, +4 introduced the OOP features to the C language. + Python: A versatile language that supports;multiple programming paradigms, including OOP. + Ct: Developed by Microsoft for its .NET framework, it's a language with strong OOP features, © Ruby: known forits-elegaht syntax, it's a purely object-oriented language. 3. Applications of OOP: + Software Development: OOP helps in modeling and designing complex software systems, makingithem more modular and easier to maintain and scale. + Game DevelopmentiGames often have hierarchies(6f classes like characters, weapons, and enemies. OOPihelps in.structuting this hierarchy. + GUI Applications: Modern graphical user interfaces are often designed using OOP principles, allowing various Ul elements to be treated as objects. Real-time Systems: Systems like air traffic control or medical monitoring systems can use OOP for modeling real-world entities like airplanes or patients. + Database Systems: Object-Oriented Databases (0008) and Object-Relational Databases (ORDB) utilize OOP concepts to design better database systems. ‘+ Simulation and Modeling: OOP can represent and simulate real-world systems, like financial systems or any physical system. MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 Simple C++ Program: In this program: +#include includes the standard input-outputstream library. ‘+ using namespace std; allows us to write cout instead of std::cout, + The main() function is the starting point of execution for the program. cout is used to print the string "Hello, World!" to the console. Note: This Notes is Creatéd by Diploma Solution Team, Don’t Sell these notes and Don’t Use this Notes without Diploma Solution AdminsPermission. It is Onl for Diploma Solution Students. Download MSBTE Diploftia All Branch - All Semester - All Subjects Notes on Google. WhatsApp No: 8108332570 YouTube: iploma Solution 1.4 Tokens, keywords, variables. constants, basic data types. User defined data types, type casting, operators, expressions. 1. Tokens: Tokens are the smallest units in a program that have meaningful representation. They are the building blocks of a program. Types of tokens in C++ include: + Keywords + Identifiers + Constants + Strings = Operators 2. Keywords: Keywords are reserved words that have special meanings in C++. Examples include int, return, void, class, if, while, and so on. You cannot use keywords as variable or function names. MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 if Statement: & e a & 2 - cer & & # & 2. Loops: Loops are used when we need to execute a block of code repeatedly based on a condition ora set of conditions. for Loop: Used when the number of iterations is known. MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 3. Variables: Variables are named memory locations used to store data. Their value can change during program execution. For instance: 4. Constants: Constants are named memory locations whose value cannot change during program execution. In C++, you can define constants using the const keyword: 5. Basic Data Types: C++ offers several fundamental data types: + int: For integers * float: For floating-point numbers + double: For double precision floating-point numbers + char: For characters + bool: For boolean values (tru@or false) 6. User-defined Data Types: In C+, you can define custom data types using structures (struct), unions (union), and classes (class). 7. Type Casting: Type casting isa way to convert’a variable ffom one data type to another. For example: 8. Operators: Operators perform operations on vatiables and values. They include: + Arithmetic operators: +, -, *, /, % + Relational operators: > Logical operatots 88H; + Assignment operato) , ote. * Others: Conditional (ternary) operator? 's;inerement ++,deerement ~, etc. 9. Expressions: Anvexpression is a combination of variables, constants, and operators written as per the syntax of C++. For example: Control structures govern the flow of a program. They determine the sequence in which statements are executed. In C++, the primary control structures are decision-making statements and loops. 1, Decision Making Statements: Decision-making structures evaluate a condition before the program proceeds to the next sequence of instructions. Based on the evaluation, certain blocks of code may or may not be executed. MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 while Loop: Used when the number of iterations is not known in advance, and the loop runs as long as the condition is true. do-while Loop: Similar to the while loop, but the loop body is executed at least once since the condition is checked after executing the loop body. 1, Scope Resolution Operator (::): The scope fesolution operator in C++ is us@d/to define a function outside a class or to access global variables inside local scopes, + Defining Functions Outside a Class: If yol!have declared a function inside a class and wish to define it outside'the Class, the scope resOlution operator is used. Accessing Global Vatiables: When a global variablei hidden by a local variable of the same name, the scope resolution operatoncai be used to refer to the global variable. 2. Memory Management Operators: In C++, dynamic memory allocation is managed with two primary operators: new and delete. ‘© new Operator: Used to allocate memory dynamically on the heap during runtime. It returns a pointer to the start of the block of memory it allocates. MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 For arrays: + delete Operator: Used to deallocate or free the memory that was previously allocated by the new operator. It helps in preventing memory leaks For arrays: It's essential to ensure thatievery memoryalllocation done using the new operator is followed by a delete opefation when that memory is néllonger required. This practice helps in efficient memory management and the prevention ofmemory leaks. 1. Arrays; ‘An array is a collection of elements of the same type; stored in contiguous memory locations, Each elemrient can be accessed directlyusinglits index. + Declaration: * Exampl + Accessing Array Elements: 2. Strings: In C+, strings are essentially arrays of characters terminated by a null character (\0). The C++ Standard Library provides a string class that simplifies string operations. + _ String Initialization using Character Arrays: © Using the string class: ‘+ String Operations: With the string class, various operations such as concatenation, substring, finding the length, and more become straightforward: MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 3. Structures: A structure (struct) is a user-defined data type that groups related variables of different data types. Structures help represent a record. + Defining a Structure: 1g a Structure: After defining the structure, you can declare structure variables and access its membersiusing the dot (.) operator. ‘= Passing Structures to Functions: Structures can be passed to functions as arguments and ¢an also be returned from functions. Note: This Notes is Creat@d by Diploma Solution Team, Don’t Sell these notes and Don't Use this Notes without Diplomig Solution Admins Permission. It is Onl for Diploma Solution Students. Download MSBTE Diploftia All Branch - All Semester - All Subjects Notes on Google. WhatsApp No: 8108332570 2s) a AY (@) +91 8108332570 a MSBTE Diploma Solution) bs www.diplomasolution.com| a » ad MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 1. Introduction: In C++, Object-Oriented Programming (OOP) is a paradigm where programs are organized around objects and classes. Here, a class provides a blueprint for creating objects (instances), and an object is a member or an instance of the class. 2. Specifying a Class: A class is defined using the class keyword, followed by the class name and the class body enclosed in curly braces. 3. Access Specifiers Access specifiers determife the visibilitYiof the members (variablesior functions) of the class. © private: Members are accessible only within the class. This is the default access level ‘+ public; Members are accessible outside the class + protected: Members are accessible within'the class and its derived classes. 4. Defining Member Functions: Member functions can be defined inside the class (inline) or outside the class using the scope resolution Operator :: * Inside the class: = Outside the class: 5. Creating Objects Once a class is defined, objects of that class can be instantiated using the class name. MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 6. Memory Alllocation for Objects: When you create an object of a class, memory is allocated for the object on the stack. However, if you want to allocate memory dynamically, you can use the new keyword, and it'll allocate memory on the heap. 1. Static Data Members: Static data members of a class are shared by all the objects of thatclass, meaning there is only one copy of a stati¢ data member, regardless of the number of objects created. They belong to the class rather than any specific object instance. ‘+ Declaration: Static datamembers are declaredhwithin the class but are defined outside the class usingtthe scope resolution operatof : 2. Static Member Functions: Like static data ihembers, static member functions also,belong to the class rather than any specific object. As @ fesult, they can only access statiédata members or other static member functions. They cannotlaccess non-statiéimembers of the class, = Usage: You can call the static member function using the class name: MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 3. Friend Functions: A friend function is a function that is not a member of a class but has access to the class's private and protected members. It is useful when two or more unrelated classes need to share functionality without exposing private data Declaration: The keyword friend precedes the function's prototype within the class definition. 1. Array of Objects: In C++, like/other data types, you can declare an array of objects, which means each element ofthe array is an instance (or object) of that class. + Decla + Example: Suppose we have a thass called! Book: You can create an aftay of Book objects a: 2. Object as Function Arguments: You can pass objects as arguments to functions. This allows functions to operate on the data contained within the objects. + Pass-by-Value: When an object is passed by value, a copy of the object is passed to the function. Any changes made to the object inside the function will not affect the original object. + Pass-by-Reference: If you want to modify the original object or avoid the overhead of copying (especially for large objects), you can pass the object by reference, MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 + Pass-by-Pointer: Alternatively, you can pass the address of the object, effectively passing it by pointer. Example Usage: Note: This Notes is\Created by Diploma Solution Team, Don’t Sell:these notes and Don’t Use this Notes without Diploma Solution Admins Permission. It's Only for Diploma Solution Students. Download MSBTE Diploma All Branch - All Semester - All Subjects Notes on Google. WhatsApp No: 8108332570 YouTube: Diploma Solution 1. Constructors: An introduction: A constructoris a Spécial member function in.a class thatis executed whenever a new object of that class is created. Constructors have the same name asthe class and don't return any value)not even void. The primary purpose of construétors is to initialize the object's attributes oiito allocate resources. 2. Types of Constructo In C+, there are several types of constructors: ‘= Default Constructor: A default constructor does not take any arguments. It either provides default values to the object attributes or sets them to zero. + Parameterized Constructor: It takes one or more parameters to initialize the object. MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 © Copy Constructor: It initializes an object using another object of the same class. The primary purpose is to copy the values of one object to another object of the same class type. © Move Constructor (C++11 onward): It "moves" the resources from one object to another, rather than copying them, which can be more efficient in cases like returning objects from functions. It takes an rvalue reference to the class type as its parameter. + Explicit Constructors (fo prevent ifplicit type conversions): Sometimes, you might want tojprevent the compiler from using a‘¢onstructor implicitly for type conversions. By declaring the constructor as explicit you can achieve this. 1. Multiple Constructors in a Class: In C+, a class ean have multiple constructors. This concept is known as constructor overloading. Each constfluctor must have a unique signatlire, which means the number and/or type of parameters mustidiffer. This allowSiObjects of the same class to be initialized in different ways based on the provided arguments. In the above example, we have three constructors for the Rectangle class. You can create a rectangle with no arguments (which defaults to a square of side 0), with two arguments specifying width and height, or with a single argument to create a square. MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 Constructors with Default Arguments: Constructors can also have default arguments. This means that if an argument is not provided when the constructor is called, the default value will be used, This can be particularly useful to provide flexibility and simplicity in creating objects. In this example, the Circle class has a constructor with a default argument for the radius. If an object is created without specifying the radius, it defaults to 1.0. 1. Introduction to Destructor: ‘A destfuctor is @ special member function of a class that is executed whenever an object of that class goes out of scope or is explicitly destroyed. Its primary purpose is to release resources that the object may have acquired during its lifetime, ensuring that resources such as memoryrfile handles, and network connections are properly released. 2. Characteristics of Destructors: + Aclass ean hayeonly,one-destructor. © Destructors eannot be overloaded. ‘= They have the same name as the class but are prefixed with altilde (~). * Destructors don't take any arguments and don't return anything, not even void. 3. Implementing a Destructor: For many classes, especially those that only use stack-allocated members, the default destructor provided by the compiler (which does nothing) is adequate. However, for classes that acquire resources like dynamic memory allocation, custom destructors are crucial, Here's an example: MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 In the above class, the constructor allocates memory dynamically, and the destructor ensures that this memory is released when the object is destroyed. 4. Behavior of Destructors: Objects in C++ can be created on the stack or the heap. Their destructors are called in different scenarios: + Forstack-allocated objects, the destructor is called automatically when the object goes out of scope. * For heap-allocated objectsyithé destructorisicalled when the delete operator is used. Note: This Notesis Created by Diploma Solution|Team/Don’t Sell thse notesand Don’t Use this Notes without Biploma Solution Admins Permission. It is Only for Diploma Solution Students. Download MSBTE Diploma All Branch - All Semester - All Subjects Notes on Google. WhatsApp No: 8108332570. YouTube: Diploma Solution MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 Unit-Ill Extending Classes using Inheritance 3.1 Introduction to Inheritance, defining a derived clas, visbty modes and effects. 1. Introduction to Inheritance: Inheritance is one of the four primary tenets of object-oriented programming (OOP). It enables the creation of a new class that is based on an existing class. The primary purpose. of inheritance is to promote code reuse and establish a natural hierarchy between classes. In C++, the class that is inherited from is called the base class or parent class, and the class that inherits is called the derived class or child class. 2. Defining a Derived Class: To define a derived class, you use the : symbol followed by the access specifier and the name of the base class. In the above code, DerivédClass inherit8from BaseClass: 3. Visibility Modes and Their Effects: There are three visibility modes in C++. inheritance: * Public Inheritance (public): ‘+ Publiofhembers of the base class be€ome public members of the derived class. © | Protected members of the base class become protected members of the derived class: + | Private members‘of the base class'are notjaccessibledirectly from the derived dass. This is the mostcommonly used mode, representing an" you have a Vehidle.class and a Car class, using public inherit of Vehicle. -a" relationship. For instance, if ince implies that a Car is a type + Protected Inheritance (protected): * Public and protected members of the base class become protected members of the derived class. * Private members of the base class are not accessible directly from the derived class. This mode is less common and represents a more restricted "is-a" relationship. * Private Inheritance (private): * Public and protected members of the base class become private members of the derived class. + Private members of the base class are not accessible directly from the derived class. MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 This mode is the least common and represents an "implemented-in-terms-of" relationship rather than an “is-a" relationship. Essentially, you're saying the derived class is implemented in terms of the base class but doesn't expose its interface to users. 1. Single Inheritance: In single inheritance, a class inherits from only one base class. This is the most straightforward form of inheritance. In this case, Derived class inherits from the Base'class. 2. Multilevel Inheritance: In multilevel inheritance, a class inherits from a base class, Which in turn inherits from another class t's like a chin of inheritance. Here, Cl inherits from Parent, and Parent inherits from Grandparent. 3. Multiple Inheritafice: le inheritance, a class*can inherit frofiT More than one base class. C++ supports multiple inheritance, but it's used with caution due to potential complications like the "diamond problem", In this scenario, Child inherits attributes and behaviors from/both Mother and Father. 4. Hierarchical Inheritance In hierarchical inheritance, multiple classes inherit from a single base class. Both Car and Boat inherit from the Vehicle class. Hybrid Inheritance: Hybrid inheritance is a combination of two or more types of inheritance mentioned above. It's a complex form of inheritance and can introduce multiple issues, especially when combined with multiple inheritance. For instance, if you have a scenario where you're using both multiple and multilevel inheritance, you're using hybrid inheritance MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 1. Virtual Base Class: In the context of multiple inheritance, a situation can arise where a derived class can inherit a base class more than once. This problem is often termed as the "diamond problem". To avoid such ambiguities, C++ introduces the concept of the virtual base class. By declaring the base class as virtual when inheriting, C+ ensures that only one copy of the base class is inherited, regardless of how many inheritance paths exist to that base In this diamond struéture, Derived class inherits Base class only once due to the virtual keyword. 2. Abstract Class: An abstract class is a class that cannot be instantiated and is meantto be subclassed by other Glasses. It often contains at least one'pure virtual function, signaling that derived classes must provide an implementation for this funetion. You cannot create objects of AbstractBase class since jt contains.a pure virtual function. 3. Constructors im)Derived Class: When creating an object of a derived class, the base class's constructor is called first, followed by the derived elass's constructor. If the base class has multiple constructors, the derived class can choose which’@ne to call usingithié member initializer list. MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 In the Derived class, the default constructor calls the default constructor of the Base class, while the parameterized constructor of Derived class calls the parameterized constructor of the Base class. Note: This Notes is Created by Diploma Solution Team, Don’t Sell these notes and Don't Use this Notes without Diploma Solution Admins Permission. It is Only for Diploma Solution Students. Download MSBTE Diploma All Branch - All Semester - All Subjects Notes on Google. WhatsApp No: 8108332570 YouTube: Diploma Solution 2s) a AY (@) +91 8108332570 a MSBTE Diploma Solution) bs www.diplomasolution.com| a » ad MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 1. Pointer Declaration: A pointer is a variable that holds the address of another variable. To declare a pointer, you use the * operator followed by the pointer's name. The data type of the pointer should match the data type of the variable whose address it will hold. 2. Pointer and Address Operators: + Address Operator (&): Used to obtain the memory address of a variable. + Pointer‘Operator (*): Also known as the déreference operator. Itis used to access the value at the address held by the pointed 3. Pointer Arithmetic: Pointers in C++ caf be incremented or decremented, which means they can point to the next or previous memory location;respectively.,Thisis\particularly useful when working with arrays. The afithmetic operations possible with pointefs are addition, subtraction, comparison, but multiplication or division is not directly applicable, ‘+ Incrementingia Pointer: IFint_ptr points to afiint which is typically 4 bytes, incrementing the pointer will move it to the next integer, 4 bytes ahead. + _Decrementing a Pointer: Pointer Difference: You can subtract two pointers to know the difference between them (provided they point to elements within the same array or block of memory). The result gives the number of elements between the two pointers. MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 + Comparing Pointers: Pointers can be compared using relational operators to determine the relative position of a 8 3 3 3 3 3 = g g 1, Pointer to Object: In C+, you can have a pointer pointing to an instance (object) of a class. This allows for dynamic allocation of objects and more flexible object management. In the above code, ptr is a pointer that paints to. the object obj of MyClass. The arrow (->) operatorlis used to access. the members of the object through the pointer. 2. This Pointer: Inside class's, member function, the this keywordis.a special pointer that points to the object fon which the function was called. Itprovides a wayto refer to the object itself. In the above class, the compare function uses the this pointer to compare the value of x of the current object with the value of x of another object. 3. Pointer to Derived Class: In inheritance, a base class pointer can point to a derived class object. This property is essential for achieving polymorphism in C+. MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 In the example, a pointer of type Base is used to point to an object of type Derived. The Use of the virtual keyword in the base class ensures that the correct show() function is called, showcasing runtime polymorphism. Polymorphism: Polymorphism, derived from the Greek words "poly" (many) and "morphism" (forms), is a fundamental concept in object-oriented programming. It allows objects of different classes to be treated as if they are objects of the same class. The essence of polymorphism is that it allows one interface-to be used for a genéral class of actions. The specific action is determined by the@kact nature of the situation. Types of Palymorphism: 1. Compile-time Polymorphism (Static Polymorphism): + Function Overloading: It occurs when multiple functions with the same name are defined in a scope. The functions must differ either by the arity (number of parameters) or the type of their parameters. + Operator Overloading: It allows developers to specify more than one definition for operators in custom data types. MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 2. Runtime Polymorphism (Dynamic Polymorphism): + Virtual Functions and Method Overriding: It occurs when a derived class provides a specific implementation of a method that is already defined in its base class. The mechanism used to achieve runtime polymorphism in C++ is the virtual function. In the aboveleode, if we have a base class\pointér pointing tia derived class object and we call the show() method, the derived class's show() method will be invoked. This is due to the virtual keyword in the base class, which ensures dynamic linkage. Note: This Notes is Created by. Diploma Solution Team, Donit Sell these notes and Don't Use this Notes without Diploma Solution Admins Permission. It if Onifor Diploma Solution Students. Download MSBTE Diploma All Branch - All Semester - All Subjects Notes on Google. WhatsApp No: 8108332570. YouTube: Diploma Solution 1. Function Overloadiny Function overloading alloWs multiple functionsiin the same scope to have the same name but different parameters. The correct function is chosen by the compiler based on the number and types of arguments passed to the function. + Example: MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 2. Operator Overloading: Operator overloading allows developers to provide a special meaning to an existing operator, so that it can be used with user-defined data types. + Overloading Unary Operators: In the above example, the unary - operator is overloaded to negate the value of the Number class. + Overloading Binary Operators Here, the binary + operator is overloaded to atid two Complex numbers. 3. Rules for Operator Overloading * Operators :: (scOpe-resoltition), . (member access), and .* (member pointer access) cannot ke overloaded. © New operators cannot becreated, andthe precedence of existing operators cannot be changed. * Overloaded Operators must either be member functions onfif they are non-members, at least one operand must be of a user-defined type. + Anoverloaded operator can have default arguments! + The = (assignment) operatoncan be overloadéd but it's often recommended to provide a copy constructor along with overloading the assignment operator. ‘+ When overloading compound assignment operators like += and a common practice to also overload their corresponding binary operators (+ and -). + The unary operators ++ and — can be overloaded to support both prefix and postfix versions. The distinction is made by the use of a dummy integer parameter for the postfix version. 1. Virtual Functions: Virtual functions enable dynamic (run-time) polymorphism in C++. They are member functions declared in a base class and overridden by a derived class. The decision about MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 which function to invoke (base or derived) is made at run-time based on the type of the object being pointed to, rather than the type of the pointer. + Example: If you have a base class pointer pointing to a derived class object and call the display() function, the derived class's display() will be executed due to the virtual keyword. 2. Rules for Virtual Functions: + A function declafed as virtual in the base class can be overridden in the derived class. * Virtual functions must be members of some class. They canhot be static members. + They cannot be a frietid of another class + Avirtual function in a base class might note used. If it's not used and not overridden in the derived class, then itremains a pure virtual function for that derived class. + Aclass containing pure virtual functions cannot be instantiated. + Ifa virtual function is defined in a base class, there's no necessity of redefining it in the derived class. 3. Pure Virtual Fun A pure virtual function is-a function declaredinja base,class that has no definition relative to the base. Itrequires that any derived classes provide a definition for this function. A class.containing a pure virtual function is termed abstraet, meaning it cannot be instantiated on itS\own. Declaring a functionlas pure virtual is done by assigning 0 inits declaration: Derived classes must provide a concrete definition for this function, otherwise, they too will become abstract. ns: Note: This Notes is Created by Diploma Solution Team, Don’t Sell these notes and Don't Use this Notes without Diploma Solution Admins Permission. It is Only for Diploma Solution Students. Download MSBTE Diploma All Branch - All Semester - All Subjects Notes on Google. WhatsApp No: 8108332570. YouTube: Diploma Solution MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 1. C+ Stream Classes: In C+, the concept of streams is used to perform input and output operations. Streams provide an abstraction that lets you think of input and output sources as sequential streams of data. The I/O in C++ is achieved through a hierarchy of stream classes provided by the Standard Library. © jos: This is the base class for all /O stream classes. It defines various member types (like pos_type and off_type) and provides basic I/O functions. + istream: This is the input stream class derived from ios and is used to perform input operations. ‘+ ostream: Derived from ios, this js the output stream class used for output operations. + ostream: This class is derived from both istréamand ostream and is used for both input and output operations. 2. Classes for File Stream Operations: For file operations, C++ provides specialized stream classes that are derived from the above-mentioned classes: ‘+ ifstream: Derived from istream, this lass represents the input file stream and is used for reading data from files. © ofstream: Derived frortOstream, this class stafids for the output file stream and is. used to write/lata to files. + fstream: Derived from iostream, this class represents the file stream generally, and it's used for both reading from and writing to files. Basic File Operation: 2. Reading froma File: string line; ‘while (getlinefinFile, line) { cout << line << endl; 1 MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 4. Closing a File: 5. File Modes: When opening a file, you can specify various modes like ios::in (for reading), ios::out (for writing), ios::app (append mode), ios::binary (binary mode), and others. 5.2 Opening files, closing tiles, reading from and writing to files. 1. Opening, In CH files are opened using the opent) function of the file stream classes (ifstream, ofstream, and fstream). When opening a file, vou can also specify the mode in which the file should be opened. The ios class provides several constants that can be used to specify the file mode: jos::in: For reading + josout: For writing + josi:app: Append mode inary: Binary mode + joss:trune: Truncate file when opening + josizate: Open and move to the end of the file 2. Closing Files: After performing the necessary operations on a file, itis essential to close it using the. closet) function. Closing a file ensures that any buffered data is written to the file and that the file is no longer available for further operations, 3. Reading from Files: There are multiple ways to read data from a file: MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 © Using >> operator: + Using getline(): + Reading single characters: 4. Writing to Files: Writing datalto a file can be accomplished using the << opetator. You can also write data line by line or as perithe required format. 1, Detection of End of Filer Detecting the end-of a file (EOF) is crucial when reading from files.1n C++, the stream classes provide methods to determiné when the end-of a filehas been reached. Using the eof{) function: The eof{) function is a member of the stream classes and returns true when the end of a file is encountered. However, relying solely on eof() can sometimes result in the last line of a file being read twice. Hence, it's often better to check the stream state directly after an input operation. Using the streams state: This is the preferred way to detect the end of a file. string line; MSBTE Diploma All Branch Notes Available in FREE Visit Now: www.diplomasolution.com YouTube: Diploma Solution WhatsApp No: 8108332570 In this method, once the getline function encounters the end of the file, it will set the EOF flag, making the while loop condition false. 2. File Modes: File modes determine how a file should be opened. They are constants provided by the ios class. + iosiiin: This mode specifies that the file should be opened for reading. Typically used with ifstream. + ios:zout: Opens the file for writing. Ifthe file already exists, its content will be truncated unless combined with ios::app. Typically used with ofstream. + ios::app: Append mode. Data written to the file will be added to the end, irrespective of the current position. jos::binary: Opens the fileiinibinary mode'rather than text, Note: This Notes is Created by Diploma Solution Team, Don't Sell these notes and Don't Use this Notes without Diploma Solution Admins Permission. It is Only for Diploma Solution Students. Download MSBTE Diploma All Branch - All Sémester - All Subjects Notes on Google. WhatsApp No: 8108332570 YouTube: Diploma Solution 2s) a AY (@) +91 8108332570 a MSBTE Diploma Solution) bs www.diplomasolution.com| a » ad

You might also like