Object Oriented Programming in C++
Introduction
- This unit introduces learners to the evolution of programming methodologies to handle software development's increasing complexity.
- Procedural programming, which involves breaking tasks into a series of functions, was the initial approach.
- Object-Oriented Programming (OOP) emerged to organize software around "objects" that combine data and actions on that data.
- Key OOP concepts include encapsulation, inheritance, and polymorphism.
- Encapsulation protects data, inheritance allows building on existing classes, and polymorphism enables functions to behave differently based on the object used.
- Mastering procedural programming basics, hands-on practice, visualizing relationships, comparing C and C++, and exploring real-world applications are recommended for effective learning.
Objectives
- Identify the evolution of programming methodologies, including procedural and object-oriented programming.
- Define the basic concepts of Object-Oriented Programming (OOP).
- List the key characteristics of OOP.
- List the primary differences between C and C++ in terms of programming paradigms, syntax, and features.
Evolution of Programming Methodologies
- Programming languages enable computers to perform various tasks.
- Machine-level language, using binary codes (0s and 1s), was the first programming language developed in the 1940s; also known as low-level programming language.
- Assembly languages, using mnemonics, were developed in the early 1950s.
- FORTRAN, the first high-level programming language, was developed in 1957.
- The 1960s saw the development of many high-level languages for science, engineering, and business.
- The 1970s and 1980s were a golden era for high-level language development.
- PASCAL, a procedural language, was developed in 1970.
- The C programming language was developed by Dennis Ritchie at Bell Labs in 1973.
- Bjarne Stroustrup at Bell Labs began developing C++ in 1980.
- Object-oriented programming gained momentum in the 1970s and early 1980s.
- Bjarne Stroustrup integrated object-oriented programming into the C language, creating C++.
- C++ is a superset of C, sharing several features and adding new ones like objects, classes, inheritance, virtual functions, and function overloading.
- The '++' in C++ symbolizes these added features.
Limitations of procedural languages:
- Procedural languages emphasize organizing program statements into procedures or functions.
- Larger programs are divided into functions or modules with defined purposes and interfaces.
- Procedural programming has problems as software size increases, mainly concerning data management.
- The focus is on actions, with data used throughout the process; data is created by variables.
- Global variables are used when multiple functions need to access data, but this can lead to accidental modification by unintended functions.
- Debugging and modification become difficult when several functions access the same data.
- The object-oriented approach solves this by modeling data and functions together, limiting data access to specific functions.
- Procedural languages have limited extensibility and support for user-defined data types.
- Object-Oriented Programming offers flexibility through the concept of classes, which help define how datatypes is handled.
- Procedural languages' program models are not closely aligned with real-world objects, making it hard to conceptualize problems.
- Object-oriented approach addresses this by conceptualizing problems as groups of objects with specific data and functionality.
- For example, in a car game, objects like player, car, and traffic signal are created.
- Languages using the object-oriented approach include C++, Java, C#, and Smalltalk.
- The course will use C++ to teach object-oriented programming.
Introduction to OOP and Its Basic Features
- OOP decomposes complex problems into manageable objects.
- Objects encapsulate data and functions, creating self-contained units which makes the program more organized.
- OOP promotes code reuse across different program parts.
- OOP introduces controlled interaction between objects, preserving data integrity.
- Objects interact by calling each other's functions, enabling collaboration, which makes OOP a powerful paradigm for building complex systems.
Fundamental concepts of OOP:
- Objects
- Classes
- Data Abstraction and Encapsulation
- Inheritance
- Polymorphism
- Dynamic Binding
- Message Passing
Objects:
- Objects are fundamental run-time entities in an object-oriented system, representing real-world elements like people, places, or abstract data types.
- Objects are chosen based on their relevance to real-world entities.
- Each object occupies memory space and has an address, similar to records or structures.
- Objects communicate by sending messages to each other. For example, a customer object might request a bank balance from an account object.
- This interaction allows objects to work together without needing to know internal details.
Classes:
- A class is a blueprint for creating objects; multiple objects with the same structure and behavior can be created from one class.
- Objects are variables of the type class, instances that carry data and behaviors defined by the class (collection of similar objects).
- For example, "mango," "apple," and "orange" can be objects of the class "fruit."
- A class is a collection of objects of a similar type with common attributes and functions.
- For example, the class "fruit" may have attributes like color and taste and functions like ripen or spoil.
- Classes are user-defined data types similar to built-in types.
- For example, fruit mango; creates an object "mango" that belongs to the class "fruit."
Data Abstraction and Encapsulation:
- Encapsulation bundles data and functions into a single unit, known as a class.
- Data within a class is not directly accessible from outside; it's accessed through functions within the class.
- These functions serve as an interface between the object's data and the rest of the program.
- The purpose of encapsulation is to protect data from unintended interference or misuse, known as data or information hiding.
- Classes use abstraction by defining objects through abstract attributes and corresponding functions.
- Data abstraction represents essential features of an object while hiding implementation details.
- Abstraction allows programmers to focus on what an object does rather than how it does it.
- It exposes necessary attributes and methods while hiding complexities.
- Data abstraction is achieved through classes, encapsulating data and functions.
- Internal workings are not visible; users interact through a simplified interface.
- For example, a "Car" class provides methods like startEngine(), drive(), and stopEngine() without revealing engine details.
- Data abstraction manages complexity, improves readability, and separates the external interface from the internal implementation.
- By focusing on abstract properties, abstraction creates simplified representations of complex systems.
- Attributes are data members, and functions are methods or member functions.
- Classes in OOP use data abstraction and are referred to as Abstract Data Types (ADT).
- This emphasizes a high-level interface, abstracting implementation details for flexible, reusable, and maintainable code.
Inheritance:
- Inheritance allows a new class (derived class or subclass) to inherit properties and behaviors (attributes and methods) from an existing class (base class or superclass).
- This creates a class hierarchy where special classes build on general ones (i.e., the process by which a class (or object) can acquire properties and behaviors from another class).
- For example, a "Bird" class can be divided into "Flying Bird" and "Nonflying Bird" subclasses, as "Flying Bird" subclass might include birds like "Robin" and "Swallow", while the "Nonflying Bird" subclass might include "Penguin" and "Kiwi".
- Inheritance promotes code reuse: common functionality is defined in a base class, and derived classes inherit it, reducing redundancy and improving maintainability.
- OOP supports polymorphism through inheritance, allowing a single function or method to work with objects of different classes.
- Example: A base class Shape has a method draw(); subclasses like Circle, Square, and Triangle can override this method, allowing flexible method invocation.
- Inheritance makes it easy to extend existing code by creating new classes based on existing ones, adding or overriding specific functionalities.
Polymorphism:
- Polymorphism, from Greek meaning "many forms/ multiple actions (Poly = Multiple, Morphing = Actions)," allows a function or operator to behave differently based on context (i.e., the same operation can exhibit different behaviors depending on the types of data involved).
- For example, addition (+) can sum numbers or concatenate strings, implemented through operator overloading.
- Function overloading is a specific type of polymorphism where a single function name performs different tasks based on the number or type of arguments.
- Example: A base class Shape defines a function Draw(), which is overridden in derived classes like Circle, Box, and Triangle.
- Each derived class provides its specific implementation of Draw(), allowing the same function name to handle different types of shapes.
- Polymorphism enhances OOP by handling different data types and operations in a unified way, leading to more dynamic and adaptable code structures.
Dynamic binding:
- Dynamic binding, also known as late binding, links a procedure call to the specific code executed at runtime.
- This allows the program to decide which specific piece of code to execute only when the program is actually running.
- Dynamic binding is associated with polymorphism and inheritance.
- In polymorphism, a function call might behave differently depending on the object at runtime.
- This is useful in class hierarchies where a base class reference points to objects of any derived class.
- The specific method called depends on the object's dynamic type at execution time.
- For example, a draw() procedure illustrates dynamic binding.
- A base class defines draw(), and derived classes (Circle, Box, Triangle) implement their versions.
- At runtime, dynamic binding ensures the draw() version specific to the object's type (Circle, Box) is executed.
- This allows for more dynamic and adaptable code, where the executed method is determined based on the actual object in use at runtime, rather than being fixed at compile time.
Message passing:
- Message passing is fundamental to how objects interact in OOP, composed of objects defined by classes.
- Objects communicate by sending and receiving messages, similar to exchanging information.
- Programming involves creating classes, instantiating objects, and establishing communication through message passing.
- Message passing allows objects to request actions, specifying the receiving object, the function to be invoked (the message), and necessary arguments.
- For example, employee.salary(name) invokes the salary function with the argument name, resulting in processing and returning information.
- Message passing models real-world interactions, making it easier to build systems that simulate real-world scenarios.
- Objects have a lifecycle: created, interact through message passing, and destroyed.
- As long as an object is alive, it can communicate with other objects, making message passing dynamic and vital.
Characteristics of OOP
- OOP addresses limitations of procedural programming, where data and functions are loosely coupled.
- OOP enhances data security and program structure by treating data as a fundamental element.
- Data is closely tied to functions that operate on it, encapsulating it within objects to prevent unintended modifications, making the program more modular and easier to manage.
- These characteristics make OOP a powerful and flexible programming paradigm.
- Emphasis on Data Rather Than Procedure: OOP focuses on data rather than the sequence of actions; data is central, ensuring integrity and correct handling.
- Programs are Divided into Objects: OOP structures programs into manageable objects, encapsulating data and methods for modularity.
- Characterization of Objects Through Data Structures: Objects are characterized by how data is organized, ensuring self-contained entities with both data and operations.
- Tying Functions with Data: Functions are bound with an object's data, restricting operations to those defined within the object, ensuring better data integrity.
- Data Hiding: OOP hides an object's internal data from external functions, preventing unauthorized access through encapsulation.
- Object Communication via Functions: Objects interact through functions, collaborating without directly exposing internal data.
- Ease of Adding New Data and Functions: New data and methods can be easily added without disrupting program structure.
- Bottom-Up Approach in Program Design: OOP starts with small, reusable objects and combines them to build complex systems.
Benefits of Object-Oriented Programming (OOP)
- Eliminating Redundant Code: Code can be reused via inheritance.
- Building Programs Efficiently: OOP enables building programs using standard modules that work together, improving productivity.
- Improving Security: Data hiding helps ensure that sensitive parts of a program are protected from being accessed or modified by other parts of the program.
- Multiple Instances: OOP makes it possible to create multiple copies (instances) of an object that can work simultaneously without affecting each other.
- Mapping Real-World Problems: Relating objects in a program to real-world problems, making the design more intuitive.
- Work Partitioning: OOP helps in dividing work among different parts of a project, making it easier to manage.
- Detailed Design: The focus on data allows us to create more detailed and accurate models of real-world problems.
- Scalability: Object-oriented systems can grow easily from small to large, adapting to more complex requirements.
- Simplified Communication: Message passing between objects makes it easier to manage interactions within the program and with external systems.
- Managing Complexity: OOP helps manage and reduce software's complexity, making it easier to develop and maintain.
Difference Between C and C++
- C is a general-purpose programming language with a flexible and compact structure, focusing on procedural programming with small functions.
- C++, derived from C, extends the language by introducing object-oriented features, allowing for both procedural and object-oriented programming.
- The main difference is that C++ supports OOP, emphasizing modular, reusable, and maintainable programs.
- OOP packages data and functions into classes, improving code organization.
- C supports only procedural programming, which is less modular.
Key differences between C and C++:
- Programming Approach: C follows a top-down approach, while C++ supports a bottom-up approach in OOP design.
- I/O Operations: C uses printf and scanf, while C++ uses cin and cout.
- Function Declaration: C++ requires functions to be declared before use, while C does not (though it's not recommended).
- Structures: C structures are data containers, while C++ structures can include member functions and access specifiers.
- Underscores in Identifiers: Identifiers beginning with double underscores are reserved.
- Automatic Return in main(): C++ does not require an explicit return 0; in main(), while C generally recommends including it.
Applications of Object-Oriented Programming (OOP)
- OOP has become popular among software engineers as it's a significant advancement in programming techniques.
- It is increasingly used in user interface design and windowing systems.
Specific Applications of OOP:
- Real-Time Systems: Beneficial for developing real-time systems that require quick and efficient processing of data and events.
- Simulation and Modeling: Used in simulation and modeling applications where complex systems need to be represented and manipulated.
- Object-Oriented Databases: Concepts are applied to create and manage databases that use objects to represent data, enhancing organization and retrieval of complex data structures.
- Hypertext, Hypermedia, and Expert Text: Utilized in creating hypertext systems, hypermedia applications, and expert systems, which require flexible and dynamic data handling.
- AI and Expert Systems: Benefits from OOP, as it helps create systems that can simulate human expertise and decision-making.
- Neural Networks and Parallel Programming: Instrumental in developing neural networks and parallel programming, where the ability to handle complex data and processes is crucial.
- Decision Support and Office Automation Systems: Used in building decision support systems and automating office tasks, improving efficiency and productivity.
- CIM/CAM/CAD Systems: Leverage OOP for designing, manufacturing, and integrating complex industrial processes.
Summary
- Computer performs a variety of tasks with the help of programming languages. In 1980, Bjarne Stroustrup, from Bell labs, began the development of the C++ language.
- OOP is a bottom-up approach, focusing on objects that encapsulate both data and functions, which helps organize programs effectively.
- In OOP, data is treated as a critical element, encapsulated within classes, thereby preventing it from being accessed or modified inadvertently, which enhances data security and integrity.
- Core concepts include encapsulation, objects and classes, and data hiding.
- OOP introduces data abstraction for essential features, inheritance for code reuse, polymorphism for varied function forms, dynamic binding for runtime code determination, and message passing for object communication.
- Benefits include reusability, and OOP is important across various fields, especially in real-time business systems.