This document provides an overview of object-oriented programming (OOP) concepts in C++. It defines key OOP concepts like class, object, inheritance, encapsulation, abstraction, polymorphism, and overloading. It provides examples to illustrate class and object, inheritance with different types, encapsulation by hiding data, and function overloading. The document was prepared by a trainee as part of a mentoring program and provides contact information for the training organization.
The document provides an introduction to object oriented programming (OOP) compared to procedural programming. It discusses key concepts in OOP like objects, classes, attributes, methods, encapsulation. Objects contain attributes (data) and methods (behaviors). Classes are templates that define common attributes and methods for a set of objects. Encapsulation involves hiding class data and implementation details through access modifiers like private and public. Examples are provided to demonstrate how to define classes and create objects in C++ code.
The document provides an overview of object-oriented programming concepts in C++. It discusses key OOP concepts like objects, classes, encapsulation, inheritance and polymorphism. It also covers procedural programming in C++ and compares it with OOP. Examples are provided to demonstrate creating classes, objects, functions, constructors and destructors. The document contains information on basic C++ programming concepts needed to understand and implement OOP principles in C++ programs.
This document provides an overview of C++ programming concepts including:
- Procedure-oriented programming focuses on tasks like reading, calculating and printing using functions, while object-oriented programming emphasizes data through objects and classes.
- Some problems with C include lack of consideration for data elements and lack of security for networks.
- C++ classes contain variables and functions to characterize objects. Data and functions are tied together and data is hidden.
- Key concepts explained include objects, member functions, constructors, destructors, inheritance and polymorphism.
- Examples demonstrate basic C++ programs, classes, objects, arrays of objects, function overloading and the this pointer.
This document provides an overview of C++ programming concepts including:
- Procedure-oriented programming focuses on tasks like reading, calculating and printing using functions, while object-oriented programming emphasizes data through objects and classes.
- C++ was developed to include object-oriented features while retaining C's simplicity, with classes, inheritance, and other features enabling abstract data types.
- Key concepts covered include classes, objects, member functions, inline functions, passing objects as parameters, returning objects, arrays of objects, and function overloading. Examples are provided to illustrate each concept.
The document discusses object oriented programming concepts like class, object, encapsulation, inheritance and polymorphism. It provides examples of defining a class with data members and member functions in C++. It also explains constructors, destructors, different types of constructors like default, parameterized and copy constructor. Examples are given to illustrate how objects are created from a class and how member functions can be defined internally or externally.
This document provides an overview of object-oriented programming (OOP) concepts, including objects, classes, inheritance, abstraction, encapsulation, polymorphism, and operator overloading. It defines objects as having properties like state and behavior. Classes are used to create objects and define their properties and methods. Inheritance allows classes to inherit attributes and methods from parent classes. Abstraction hides irrelevant details and focuses on important properties. Encapsulation hides implementation details and exposes a public interface. Polymorphism allows objects to take different forms. Operator overloading allows operators to perform different tasks based on arguments. Examples are provided to illustrate key concepts.
This document provides an overview of object-oriented programming (OOP) concepts in C++. It defines key OOP concepts like class, object, inheritance, encapsulation, abstraction, polymorphism, and overloading. It provides examples to illustrate class and object, inheritance with different types, encapsulation by hiding data, and function overloading. The document was prepared by a trainee as part of a mentoring program and provides contact information for the training organization.
The document provides an introduction to object oriented programming (OOP) compared to procedural programming. It discusses key concepts in OOP like objects, classes, attributes, methods, encapsulation. Objects contain attributes (data) and methods (behaviors). Classes are templates that define common attributes and methods for a set of objects. Encapsulation involves hiding class data and implementation details through access modifiers like private and public. Examples are provided to demonstrate how to define classes and create objects in C++ code.
The document provides an overview of object-oriented programming concepts in C++. It discusses key OOP concepts like objects, classes, encapsulation, inheritance and polymorphism. It also covers procedural programming in C++ and compares it with OOP. Examples are provided to demonstrate creating classes, objects, functions, constructors and destructors. The document contains information on basic C++ programming concepts needed to understand and implement OOP principles in C++ programs.
This document provides an overview of C++ programming concepts including:
- Procedure-oriented programming focuses on tasks like reading, calculating and printing using functions, while object-oriented programming emphasizes data through objects and classes.
- Some problems with C include lack of consideration for data elements and lack of security for networks.
- C++ classes contain variables and functions to characterize objects. Data and functions are tied together and data is hidden.
- Key concepts explained include objects, member functions, constructors, destructors, inheritance and polymorphism.
- Examples demonstrate basic C++ programs, classes, objects, arrays of objects, function overloading and the this pointer.
This document provides an overview of C++ programming concepts including:
- Procedure-oriented programming focuses on tasks like reading, calculating and printing using functions, while object-oriented programming emphasizes data through objects and classes.
- C++ was developed to include object-oriented features while retaining C's simplicity, with classes, inheritance, and other features enabling abstract data types.
- Key concepts covered include classes, objects, member functions, inline functions, passing objects as parameters, returning objects, arrays of objects, and function overloading. Examples are provided to illustrate each concept.
The document discusses object oriented programming concepts like class, object, encapsulation, inheritance and polymorphism. It provides examples of defining a class with data members and member functions in C++. It also explains constructors, destructors, different types of constructors like default, parameterized and copy constructor. Examples are given to illustrate how objects are created from a class and how member functions can be defined internally or externally.
This document provides an overview of object-oriented programming (OOP) concepts, including objects, classes, inheritance, abstraction, encapsulation, polymorphism, and operator overloading. It defines objects as having properties like state and behavior. Classes are used to create objects and define their properties and methods. Inheritance allows classes to inherit attributes and methods from parent classes. Abstraction hides irrelevant details and focuses on important properties. Encapsulation hides implementation details and exposes a public interface. Polymorphism allows objects to take different forms. Operator overloading allows operators to perform different tasks based on arguments. Examples are provided to illustrate key concepts.
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxDeepasCSE
Certainly, here's a brief explanation of constructors, destructors, and operator overloading without using code:
Constructors: Constructors are special methods used to initialize objects of a class. They set the initial state of an object when it is created.
Destructors: Destructors are special methods used to clean up resources and perform necessary cleanup when an object is no longer needed or goes out of scope. They ensure proper resource management.
Operator Overloading: Operator overloading is a feature that allows you to define custom behaviors for operators such as +, -, *, /, etc., when they are applied to objects of your class. It enables you to work with objects in a way that is meaningful for your specific class.
Constructors can be of different types:
Default Constructors: Initialize objects with default values.
Parameterized Constructors: Accept arguments to initialize objects with specific values.
Copy Constructors: Create a new object as a copy of an existing object.
Constructor Overloading: A class can have multiple constructors with different parameter lists, providing flexibility in object initialization.
Destructors are executed automatically when an object is destroyed. They are essential for releasing resources like memory, file handles, or network connections, ensuring proper cleanup and preventing resource leaks.
Operator overloading enables you to define how operators work with objects of your class. For instance, you can specify what the + operator does when applied to two objects of your class, allowing for custom operations that make sense in the context of your class's functionality.
In summary, constructors initialize objects, destructors handle cleanup, and operator overloading allows custom operations with operators when working with objects. These features are crucial for building custom classes in object-oriented programming.
The document discusses object oriented programming concepts in C++ like classes, objects, data members, member functions etc. It provides code examples to demonstrate defining classes with data members and member functions, creating objects of a class, accessing data members and calling member functions. It also shows the difference between declaring members as public or private. One example creates an Employee class with functions to get employee details like salary, working hours and calculate final salary. Another example creates an Employee class to store and print details of 3 employees like name, year of joining and address.
This document discusses C++ as an object-oriented language. It describes key concepts like classes, objects, data members, member functions, access specifiers (public, private, protected), constructors, and destructors. Classes allow the combination of data and related functions that represent real-world objects. Constructors initialize objects, while destructors handle cleanup when objects are destroyed. Access specifiers determine visibility and access to class members from within and outside the class.
OOP stands for Object-Oriented Programming. It involves creating objects that contain both data and methods. Classes act as templates for objects and define their attributes and behaviors. Some advantages of OOP include reusability, organization, and reduced repetition of code. Classes contain fields to store data and methods to perform actions on that data. Objects are instances of classes that inherit all fields and methods. Constructors initialize objects and can set initial field values. Arrays can store multiple objects. Dynamic arrays allow adding elements at runtime. Partial classes allow splitting a class definition across multiple files.
Object-oriented programming (OOP) with Complete understanding modulesDurgesh Singh
The document provides an overview of object-oriented programming concepts in C# such as classes, objects, encapsulation, inheritance, polymorphism, and reusability. It discusses class definitions, constructors, destructors, access modifiers, and provides examples of creating classes and class libraries. Key topics covered include defining fields and methods, instantiating objects, using constructors, creating partial and static classes, and building class library components for reuse across applications.
Introduction to object oriented programming conceptsGanesh Karthik
OOPS concepts such as class, object, encapsulation, inheritance, polymorphism are introduced. A class is a collection of objects that defines common properties and behaviors. An object is an instance of a class. Encapsulation binds data and methods together, abstraction hides implementation details, and inheritance allows deriving new classes from existing classes. Polymorphism allows the same message to be processed in different ways. Constructors and destructors are special methods used for object initialization and cleanup.
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptxDeepasCSE
Object-Oriented Programming (OOP) is a programming paradigm that focuses on organizing and modeling software as a collection of objects. In OOP, objects are instances of classes, which serve as blueprints or templates for defining the structure and behavior of those objects. OOP is built on several key principles and concepts, which include:
Objects: Objects are the basic building blocks of an OOP system. They represent real-world entities, and they encapsulate both data (attributes or properties) and behavior (methods or functions) that operate on that data.
Classes: Classes are the templates or blueprints from which objects are created. They define the attributes and methods that objects of the class will possess. Classes enable the concept of abstraction, allowing you to create objects with common characteristics and behaviors.
Encapsulation: Encapsulation is the concept of bundling data (attributes) and methods (functions) that operate on that data into a single unit, i.e., a class. This unit is called an object. Encapsulation restricts access to the internal state of an object, providing data hiding and promoting information hiding, which helps manage complexity and reduces potential issues.
Inheritance: Inheritance is a mechanism that allows a class (a child or derived class) to inherit the attributes and methods of another class (a parent or base class). This promotes code reusability and the creation of specialized classes.
Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a common base class. It enables the use of a single interface to represent a general class of actions. Polymorphism can take the form of method overriding (a subclass provides a specific implementation of a method defined in its superclass) or method overloading (multiple methods with the same name but different parameters).
Abstraction: Abstraction is the process of simplifying complex reality by modeling classes based on the essential properties and behaviors. It hides the unnecessary details while providing a clear and well-defined interface for interacting with objects.
Object-Oriented Programming is widely used in various programming languages like C++, Java, C#, Python, and more. It promotes code organization, modularity, and the modeling of real-world entities in a way that makes it easier to design, develop, and maintain software systems. OOP is particularly suited for large and complex projects where code readability, reusability, and maintainability are critical.
This document provides an overview of the C++ programming language. It discusses key C++ concepts like classes, objects, functions, and data types. Some key points:
- C++ is an object-oriented language that is an extension of C with additional features like classes and inheritance.
- Classes allow programmers to combine data and functions to model real-world entities. Objects are instances of classes.
- The document defines common C++ terms like keywords, identifiers, constants, and operators. It also provides examples of basic programs.
- Functions are described as modular and reusable blocks of code. Parameter passing techniques like pass-by-value and pass-by-reference are covered.
- Other concepts covered include
The document discusses object-oriented programming concepts like classes, objects, member functions, data members, constructors, and encapsulation. It explains that a class defines the structure and behavior of objects, with data members representing attributes and member functions representing behaviors. Constructors initialize an object's data when it is created. Encapsulation protects data by making it private and only accessible through public member functions.
Object Oriented Programming using C++(UNIT 1)SURBHI SAROHA
This document provides an introduction to object-oriented programming (OOP) concepts using C++. It defines key OOP terms like class, object, encapsulation, inheritance, polymorphism and abstraction. It provides examples of different types of inheritance in C++ like single, multiple, hierarchical and hybrid inheritance. It also outlines advantages of OOP like easier troubleshooting, code reusability, increased productivity, reduced data redundancy, and flexible code.
This code will generate a compile time error as Base is an abstract class due to pure virtual function show(). An abstract class cannot be instantiated.
C# classes allow for modularity, data encapsulation, inheritance, and polymorphism. They act as blueprints for generating object instances. The document discusses key object-oriented programming concepts in C# like encapsulation, inheritance, polymorphism, casting, exception handling, garbage collection, interfaces, collections, comparables, and delegates. It provides examples to illustrate concepts like shallow cloning using ICloneable, implementing IComparable, overloading operators, and using XML documentation comments.
The document outlines a lecture plan for object oriented programming. It covers topics like structures and classes, function overloading, constructors and destructors, operator overloading, inheritance, polymorphism, and file streams. It provides examples to explain concepts like structures, classes, access specifiers, friend functions, and operator overloading. The document also includes questions for students to practice these concepts.
The document provides information about classes and objects in C++. Some key points:
- A class defines a user-defined data type by binding data and functions together. It contains data members and member functions.
- Classes have access specifiers like private, public, and protected that control access to members.
- Objects are instances of a class that allocate memory dynamically. They are used to access class members by using dot operator.
- Member functions can access private data members while non-member functions cannot. Memory is separately allocated for each object's data members.
- Static members have single copy shared among all objects rather than each object having its own copy. They are initialized only once.
The document discusses structures and classes in C++. It defines a structure called student with data members like name and roll number. It then defines a class called person with data members name and number and demonstrates creating an object of the class and accessing its members. The document also discusses concepts like defining member functions inside and outside classes, access specifiers, nesting member functions, and making outside member functions inline.
2nd puc computer science chapter 8 function overloading ,types of function overloading ,syntax function overloading ,example function overloading
inline function, friend function ,
1. The document provides an introduction to object-oriented programming concepts and C++ programming.
2. It discusses the need for OOP over procedure-oriented programming and highlights the differences between the two approaches.
3. The document then covers basic C++ concepts like data types, functions, classes, inheritance and polymorphism through examples.
This document discusses abstraction in C++. It defines abstraction as representing crucial features without including unnecessary details. There are two types of abstraction in C++ - data abstraction, which hides data information, and control abstraction, which hides implementation information. Abstract classes can be used to provide structure without implementation. The document provides an example program using an abstract class and discusses applications like increased reusability and security from hiding details. Potential downsides of abstraction are discussed, like reduced performance from extra handling of abstraction.
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxDeepasCSE
Certainly, here's a brief explanation of constructors, destructors, and operator overloading without using code:
Constructors: Constructors are special methods used to initialize objects of a class. They set the initial state of an object when it is created.
Destructors: Destructors are special methods used to clean up resources and perform necessary cleanup when an object is no longer needed or goes out of scope. They ensure proper resource management.
Operator Overloading: Operator overloading is a feature that allows you to define custom behaviors for operators such as +, -, *, /, etc., when they are applied to objects of your class. It enables you to work with objects in a way that is meaningful for your specific class.
Constructors can be of different types:
Default Constructors: Initialize objects with default values.
Parameterized Constructors: Accept arguments to initialize objects with specific values.
Copy Constructors: Create a new object as a copy of an existing object.
Constructor Overloading: A class can have multiple constructors with different parameter lists, providing flexibility in object initialization.
Destructors are executed automatically when an object is destroyed. They are essential for releasing resources like memory, file handles, or network connections, ensuring proper cleanup and preventing resource leaks.
Operator overloading enables you to define how operators work with objects of your class. For instance, you can specify what the + operator does when applied to two objects of your class, allowing for custom operations that make sense in the context of your class's functionality.
In summary, constructors initialize objects, destructors handle cleanup, and operator overloading allows custom operations with operators when working with objects. These features are crucial for building custom classes in object-oriented programming.
The document discusses object oriented programming concepts in C++ like classes, objects, data members, member functions etc. It provides code examples to demonstrate defining classes with data members and member functions, creating objects of a class, accessing data members and calling member functions. It also shows the difference between declaring members as public or private. One example creates an Employee class with functions to get employee details like salary, working hours and calculate final salary. Another example creates an Employee class to store and print details of 3 employees like name, year of joining and address.
This document discusses C++ as an object-oriented language. It describes key concepts like classes, objects, data members, member functions, access specifiers (public, private, protected), constructors, and destructors. Classes allow the combination of data and related functions that represent real-world objects. Constructors initialize objects, while destructors handle cleanup when objects are destroyed. Access specifiers determine visibility and access to class members from within and outside the class.
OOP stands for Object-Oriented Programming. It involves creating objects that contain both data and methods. Classes act as templates for objects and define their attributes and behaviors. Some advantages of OOP include reusability, organization, and reduced repetition of code. Classes contain fields to store data and methods to perform actions on that data. Objects are instances of classes that inherit all fields and methods. Constructors initialize objects and can set initial field values. Arrays can store multiple objects. Dynamic arrays allow adding elements at runtime. Partial classes allow splitting a class definition across multiple files.
Object-oriented programming (OOP) with Complete understanding modulesDurgesh Singh
The document provides an overview of object-oriented programming concepts in C# such as classes, objects, encapsulation, inheritance, polymorphism, and reusability. It discusses class definitions, constructors, destructors, access modifiers, and provides examples of creating classes and class libraries. Key topics covered include defining fields and methods, instantiating objects, using constructors, creating partial and static classes, and building class library components for reuse across applications.
Introduction to object oriented programming conceptsGanesh Karthik
OOPS concepts such as class, object, encapsulation, inheritance, polymorphism are introduced. A class is a collection of objects that defines common properties and behaviors. An object is an instance of a class. Encapsulation binds data and methods together, abstraction hides implementation details, and inheritance allows deriving new classes from existing classes. Polymorphism allows the same message to be processed in different ways. Constructors and destructors are special methods used for object initialization and cleanup.
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptxDeepasCSE
Object-Oriented Programming (OOP) is a programming paradigm that focuses on organizing and modeling software as a collection of objects. In OOP, objects are instances of classes, which serve as blueprints or templates for defining the structure and behavior of those objects. OOP is built on several key principles and concepts, which include:
Objects: Objects are the basic building blocks of an OOP system. They represent real-world entities, and they encapsulate both data (attributes or properties) and behavior (methods or functions) that operate on that data.
Classes: Classes are the templates or blueprints from which objects are created. They define the attributes and methods that objects of the class will possess. Classes enable the concept of abstraction, allowing you to create objects with common characteristics and behaviors.
Encapsulation: Encapsulation is the concept of bundling data (attributes) and methods (functions) that operate on that data into a single unit, i.e., a class. This unit is called an object. Encapsulation restricts access to the internal state of an object, providing data hiding and promoting information hiding, which helps manage complexity and reduces potential issues.
Inheritance: Inheritance is a mechanism that allows a class (a child or derived class) to inherit the attributes and methods of another class (a parent or base class). This promotes code reusability and the creation of specialized classes.
Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a common base class. It enables the use of a single interface to represent a general class of actions. Polymorphism can take the form of method overriding (a subclass provides a specific implementation of a method defined in its superclass) or method overloading (multiple methods with the same name but different parameters).
Abstraction: Abstraction is the process of simplifying complex reality by modeling classes based on the essential properties and behaviors. It hides the unnecessary details while providing a clear and well-defined interface for interacting with objects.
Object-Oriented Programming is widely used in various programming languages like C++, Java, C#, Python, and more. It promotes code organization, modularity, and the modeling of real-world entities in a way that makes it easier to design, develop, and maintain software systems. OOP is particularly suited for large and complex projects where code readability, reusability, and maintainability are critical.
This document provides an overview of the C++ programming language. It discusses key C++ concepts like classes, objects, functions, and data types. Some key points:
- C++ is an object-oriented language that is an extension of C with additional features like classes and inheritance.
- Classes allow programmers to combine data and functions to model real-world entities. Objects are instances of classes.
- The document defines common C++ terms like keywords, identifiers, constants, and operators. It also provides examples of basic programs.
- Functions are described as modular and reusable blocks of code. Parameter passing techniques like pass-by-value and pass-by-reference are covered.
- Other concepts covered include
The document discusses object-oriented programming concepts like classes, objects, member functions, data members, constructors, and encapsulation. It explains that a class defines the structure and behavior of objects, with data members representing attributes and member functions representing behaviors. Constructors initialize an object's data when it is created. Encapsulation protects data by making it private and only accessible through public member functions.
Object Oriented Programming using C++(UNIT 1)SURBHI SAROHA
This document provides an introduction to object-oriented programming (OOP) concepts using C++. It defines key OOP terms like class, object, encapsulation, inheritance, polymorphism and abstraction. It provides examples of different types of inheritance in C++ like single, multiple, hierarchical and hybrid inheritance. It also outlines advantages of OOP like easier troubleshooting, code reusability, increased productivity, reduced data redundancy, and flexible code.
This code will generate a compile time error as Base is an abstract class due to pure virtual function show(). An abstract class cannot be instantiated.
C# classes allow for modularity, data encapsulation, inheritance, and polymorphism. They act as blueprints for generating object instances. The document discusses key object-oriented programming concepts in C# like encapsulation, inheritance, polymorphism, casting, exception handling, garbage collection, interfaces, collections, comparables, and delegates. It provides examples to illustrate concepts like shallow cloning using ICloneable, implementing IComparable, overloading operators, and using XML documentation comments.
The document outlines a lecture plan for object oriented programming. It covers topics like structures and classes, function overloading, constructors and destructors, operator overloading, inheritance, polymorphism, and file streams. It provides examples to explain concepts like structures, classes, access specifiers, friend functions, and operator overloading. The document also includes questions for students to practice these concepts.
The document provides information about classes and objects in C++. Some key points:
- A class defines a user-defined data type by binding data and functions together. It contains data members and member functions.
- Classes have access specifiers like private, public, and protected that control access to members.
- Objects are instances of a class that allocate memory dynamically. They are used to access class members by using dot operator.
- Member functions can access private data members while non-member functions cannot. Memory is separately allocated for each object's data members.
- Static members have single copy shared among all objects rather than each object having its own copy. They are initialized only once.
The document discusses structures and classes in C++. It defines a structure called student with data members like name and roll number. It then defines a class called person with data members name and number and demonstrates creating an object of the class and accessing its members. The document also discusses concepts like defining member functions inside and outside classes, access specifiers, nesting member functions, and making outside member functions inline.
2nd puc computer science chapter 8 function overloading ,types of function overloading ,syntax function overloading ,example function overloading
inline function, friend function ,
1. The document provides an introduction to object-oriented programming concepts and C++ programming.
2. It discusses the need for OOP over procedure-oriented programming and highlights the differences between the two approaches.
3. The document then covers basic C++ concepts like data types, functions, classes, inheritance and polymorphism through examples.
This document discusses abstraction in C++. It defines abstraction as representing crucial features without including unnecessary details. There are two types of abstraction in C++ - data abstraction, which hides data information, and control abstraction, which hides implementation information. Abstract classes can be used to provide structure without implementation. The document provides an example program using an abstract class and discusses applications like increased reusability and security from hiding details. Potential downsides of abstraction are discussed, like reduced performance from extra handling of abstraction.
Similar to Object Oriented Programming using C++: Ch06 Objects and Classes.pptx (20)
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMSIJNSA Journal
The smart irrigation system represents an innovative approach to optimize water usage in agricultural and landscaping practices. The integration of cutting-edge technologies, including sensors, actuators, and data analysis, empowers this system to provide accurate monitoring and control of irrigation processes by leveraging real-time environmental conditions. The main objective of a smart irrigation system is to optimize water efficiency, minimize expenses, and foster the adoption of sustainable water management methods. This paper conducts a systematic risk assessment by exploring the key components/assets and their functionalities in the smart irrigation system. The crucial role of sensors in gathering data on soil moisture, weather patterns, and plant well-being is emphasized in this system. These sensors enable intelligent decision-making in irrigation scheduling and water distribution, leading to enhanced water efficiency and sustainable water management practices. Actuators enable automated control of irrigation devices, ensuring precise and targeted water delivery to plants. Additionally, the paper addresses the potential threat and vulnerabilities associated with smart irrigation systems. It discusses limitations of the system, such as power constraints and computational capabilities, and calculates the potential security risks. The paper suggests possible risk treatment methods for effective secure system operation. In conclusion, the paper emphasizes the significant benefits of implementing smart irrigation systems, including improved water conservation, increased crop yield, and reduced environmental impact. Additionally, based on the security analysis conducted, the paper recommends the implementation of countermeasures and security approaches to address vulnerabilities and ensure the integrity and reliability of the system. By incorporating these measures, smart irrigation technology can revolutionize water management practices in agriculture, promoting sustainability, resource efficiency, and safeguarding against potential security threats.
Embedded machine learning-based road conditions and driving behavior monitoringIJECEIAES
Car accident rates have increased in recent years, resulting in losses in human lives, properties, and other financial costs. An embedded machine learning-based system is developed to address this critical issue. The system can monitor road conditions, detect driving patterns, and identify aggressive driving behaviors. The system is based on neural networks trained on a comprehensive dataset of driving events, driving styles, and road conditions. The system effectively detects potential risks and helps mitigate the frequency and impact of accidents. The primary goal is to ensure the safety of drivers and vehicles. Collecting data involved gathering information on three key road events: normal street and normal drive, speed bumps, circular yellow speed bumps, and three aggressive driving actions: sudden start, sudden stop, and sudden entry. The gathered data is processed and analyzed using a machine learning system designed for limited power and memory devices. The developed system resulted in 91.9% accuracy, 93.6% precision, and 92% recall. The achieved inference time on an Arduino Nano 33 BLE Sense with a 32-bit CPU running at 64 MHz is 34 ms and requires 2.6 kB peak RAM and 139.9 kB program flash memory, making it suitable for resource-constrained embedded systems.
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...IJECEIAES
Climate change's impact on the planet forced the United Nations and governments to promote green energies and electric transportation. The deployments of photovoltaic (PV) and electric vehicle (EV) systems gained stronger momentum due to their numerous advantages over fossil fuel types. The advantages go beyond sustainability to reach financial support and stability. The work in this paper introduces the hybrid system between PV and EV to support industrial and commercial plants. This paper covers the theoretical framework of the proposed hybrid system including the required equation to complete the cost analysis when PV and EV are present. In addition, the proposed design diagram which sets the priorities and requirements of the system is presented. The proposed approach allows setup to advance their power stability, especially during power outages. The presented information supports researchers and plant owners to complete the necessary analysis while promoting the deployment of clean energy. The result of a case study that represents a dairy milk farmer supports the theoretical works and highlights its advanced benefits to existing plants. The short return on investment of the proposed approach supports the paper's novelty approach for the sustainable electrical system. In addition, the proposed system allows for an isolated power setup without the need for a transmission line which enhances the safety of the electrical network
Introduction- e - waste – definition - sources of e-waste– hazardous substances in e-waste - effects of e-waste on environment and human health- need for e-waste management– e-waste handling rules - waste minimization techniques for managing e-waste – recycling of e-waste - disposal treatment methods of e- waste – mechanism of extraction of precious metal from leaching solution-global Scenario of E-waste – E-waste in India- case studies.
A review on techniques and modelling methodologies used for checking electrom...nooriasukmaningtyas
The proper function of the integrated circuit (IC) in an inhibiting electromagnetic environment has always been a serious concern throughout the decades of revolution in the world of electronics, from disjunct devices to today’s integrated circuit technology, where billions of transistors are combined on a single chip. The automotive industry and smart vehicles in particular, are confronting design issues such as being prone to electromagnetic interference (EMI). Electronic control devices calculate incorrect outputs because of EMI and sensors give misleading values which can prove fatal in case of automotives. In this paper, the authors have non exhaustively tried to review research work concerned with the investigation of EMI in ICs and prediction of this EMI using various modelling methodologies and measurement setups.
Using recycled concrete aggregates (RCA) for pavements is crucial to achieving sustainability. Implementing RCA for new pavement can minimize carbon footprint, conserve natural resources, reduce harmful emissions, and lower life cycle costs. Compared to natural aggregate (NA), RCA pavement has fewer comprehensive studies and sustainability assessments.
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...University of Maribor
Slides from talk presenting:
Aleš Zamuda: Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapter and Networking.
Presentation at IcETRAN 2024 session:
"Inter-Society Networking Panel GRSS/MTT-S/CIS
Panel Session: Promoting Connection and Cooperation"
IEEE Slovenia GRSS
IEEE Serbia and Montenegro MTT-S
IEEE Slovenia CIS
11TH INTERNATIONAL CONFERENCE ON ELECTRICAL, ELECTRONIC AND COMPUTING ENGINEERING
3-6 June 2024, Niš, Serbia
International Conference on NLP, Artificial Intelligence, Machine Learning an...gerogepatton
International Conference on NLP, Artificial Intelligence, Machine Learning and Applications (NLAIM 2024) offers a premier global platform for exchanging insights and findings in the theory, methodology, and applications of NLP, Artificial Intelligence, Machine Learning, and their applications. The conference seeks substantial contributions across all key domains of NLP, Artificial Intelligence, Machine Learning, and their practical applications, aiming to foster both theoretical advancements and real-world implementations. With a focus on facilitating collaboration between researchers and practitioners from academia and industry, the conference serves as a nexus for sharing the latest developments in the field.
2. Introduction
Previously, programmers starting a project would sit down almost immediately
and start writing code.
As programming projects became large and more complicated, it was found
that this approach did not work very well. The problem was complexity.
Large programs are probably the most complicated entities ever created by
humans.
Because of this complexity, programs are prone to error, and software errors
can be expensive and even life threatening (in air traffic control, for example).
Three major innovations in programming have been devised to cope with the
problem of complexity.
2
3. Object Oriented Programming
Object Oriented Programming offers a new and powerful way to cope with
complexity.
Instead of viewing a program as a series of steps to be carried out, it views it
as a group of objects that have certain properties and can take certain actions.
This may sound obscure until you learn more about it, but it results in
programs that are clearer, more reliable, and more easily maintained.
A major goal of this course is to teach object-oriented programming using C++
and cover all its major features.
3
4. The Unified Modeling Language
The Unified Modeling Language (UML) is a graphical language consisting of
many kinds of diagrams.
It helps program analysts figure out what a program should do, and helps
programmers design and understand how a program works.
The UML is a powerful tool that can make programming easier and more
effective.
We introduce each UML feature where it will help to clarify the OOP topic
being discussed.
In this way you learn the UML painlessly at the same time the UML helps you
to learn C++.
4
5. Class
A class serves as a plan, or template. It specifies what data and what functions
will be included in objects of that class.
Defining the class doesn’t create any objects, just as the type int doesn’t
create any variables.
A class is thus a description of a number of similar objects.
5
functions data
A class encapsulates
attributes and functions
6. Example 1: A Simple Class
#include <iostream>
#include <stdlib.h>
using namespace std;
class student { // define a class (a concept)
private:
int age; // class data (attributes)
public:
void set_age(int g) { // member function
age = g; // to set age
}
void show_age() { // member function
// to display age
cout << "I am " << age
<< " Years Old."<< endl;
}
};
6
int main() {
student Ali, Usman; // define two objects
// of class student
Ali.set_age(21); // call member function
Usman.set_age(18); // to set age
Ali.show_age(); // call member function
Usman.show_age(); // to display age
system("PAUSE");
return 0;
}
7. Classes and Objects
An object has the same relationship to a class that a variable has to a data
type.
An object is said to be an instance of a class, in the same way my Corolla is an
instance of a vehicle.
In the program the class , whose name is student, is defined in the first part of
the program.
In main(), we define two objects Ali and Usman that are instances of that
class.
Each of the two objects is given a value, and each displays its value.
7
9. Defining the Class
The definition starts with the keyword class, followed by the class name—
student in this Example.
The body of the class is delimited by braces and terminated by a semicolon.
An object has the same relationship to a class that a variable has to a data
type.
A key feature of object-oriented programming is data hiding. it means that
data is concealed within a class so that it cannot be accessed mistakenly by
functions outside the class.
The primary mechanism for hiding data is to put it in a class and make it
private.
9
10. Defining the Class
private data or functions can only be accessed from within the class.
public data or functions, on the other hand, are accessible from outside the
class.
The data member age follows the keyword private, so it can be accessed from
within the class, but not from outside.
Member functions (also called methods or messages) are functions that are
included within a class.
There are two member functions in student class:
set_age() and show_age().
10
11. Defining the Class
Because set_age() and show_age()
follow the keyword public, they can
be accessed from outside the class.
In a class the functions do not occupy
memory until an object of the class is
created.
11
12. Defining the Class
Remember that the definition of the class student does not create any
objects. It only describes how they will look when they are created.
Defining objects means creating them. This is also called instantiating them,
because an instance of the class is created. An object is an instance of a class.
ali.set_age(21); This syntax is used to call a member function that is
associated with a specific object ali.
Member functions of a class can be accessed only by an object of that class.
12
13. Example 2: Using Mobile Phone as an Object (1/2)
// mobile.cpp demonstrates mobile phone as an object
#include <iostream>
#include <stdlib.h>
using namespace std;
class mobile // class name should be
{ // the name of a concept
private:
string company_name;
string model_number;
string emi_number;
float cost;
public:
void set_info(string cn, string mn, string emi, float price) { // set data
company_name = cn;
model_number = mn;
emi_number = emi;
cost = price;
}
13
14. Example 2: Using Mobile Phone as an Object (2/2)
14
void show_info()
{ // display data
cout << "Company = " << company_name.data() << endl;
cout << "Model = " << model_number.data() << endl;
cout << "EMI = " << emi_number.data() << endl;
cout << "Cost = " << cost << endl;
}
};
int main(){
mobile m1; // define object of class part
// call member function set_nfo()
m1.set_info("QMobile", "Noir A950", "dont know :)", 25000.0F);
// now call member function show_info()
m1.show_info();
system("PAUSE");
return 0;
}
15. Using Mobile Phone as an Object
If you were designing an inventory program you might actually want to create
a class something like mobile.
It’s an example of a C++ object representing a physical object in the real
world—a mobile phone.
Standard C++ includes a new class called string.
Using string object, you no longer need to worry about creating an array of the
right size to hold string variables.
The string class assumes all the responsibility for memory management.
15
16. Example 3: Using Class to Represent Height (1/2)
#include <iostream>
#include <stdlib.h>
using namespace std;
class Height{ // A Height class
private:
int feet; float inches;
public:
void set(int ft, float in){
feet = ft; inches = in;
}
void get(){ // get height information from user
cout << "nEnter Your Height Information "<<endl;
cout << "Enter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
void show(){ // display height information
cout << "Height = "<< feet << " feet and " << inches
<< " inches."<<endl;
}
};
16
17. Example 3: Using Class to Represent Height (2/2)
int main()
{
Height H1, H2; // define two height objects
H1.set(4, 9.35F); // set feet = 4 and inches = 9.35 in H1 object
H2.get(); // get feet and inches info from user for H2
// display height information from H1 and H2 Objects
cout << "For H1, "; H1.show();
cout << "For H2, "; H2.show();
system("PAUSE");
return 0;
}
17
18. Constructors
We see that member functions can be used to give values
to the data items in an object.
Sometimes, however, it’s convenient if an object can initialize itself when it’s
first created, without requiring a separate call to a member function.
Automatic initialization is carried out using a special member function called a
constructor.
A constructor is a member function that is executed automatically whenever
an object is created.
Constructor has the same name of class and it has no return type.
18
19. Example 4: Constructors A House Example (1/2)
#include <iostream> // A Constructor Example
#include <stdlib.h>
using namespace std;
class House{
private:
double area; // area in square feet
public:
House() : area(1000){ /* a zero (no) argument constructor */
cout<< "A House Created n"; /* */
} /* */
void set_area(double a)
{ area = a; }
double return_area()
{ return area; }
void get_area(){ // get area info from user
cout << "What is the area of House in Square Feet:";
cin >> area;
}
};
19
20. Example 4: Constructors A House Example (2/2)
int main()
{
House H1, H2; /* define two objects and call constructor */
cout << "default area of House H1 is = "
<< H1.return_area() << endl;
cout << "default area of House H2 is = "
<< H2.return_area() << endl;
H1.set_area(1500);
H2.get_area();
cout << "Now Area of House H1 is = "
<< H1.return_area() << " Square Feet"<<endl;
cout << "Now Area of House H2 is = "
<< H2.return_area() << " Square Feet"<<endl;
system("PAUSE");
return 0;
}
20
21. Example 5: Constructors A Dice Example (1/2)
#include <iostream> // for cin and cout
#include <stdlib.h> // for rand(), srand() and system()
#include <time.h> // for time()
using namespace std;
class Dice{
private:
int number;
public:
Dice():number(1){ /* A zero (no) argument constructor */
/* Sets the default number rolled by a dice to 1 */
/* seed random number generator with current system time */
srand(time(0)); /* Seed with Current time of PC */
} /* */
int roll() // Function to roll a dice.
{ // This function uses a random number generator to randomly
// generate a number between 1 and 6, and stores the number
// in the instance variable number and returns the number.
number = rand() % 6 + 1;
return number;
}
21
22. Example 5: Constructors A Dice Example (2/2)
int get_number() // Function to return the number on the top face
{ // of the die. It returns the value of the variable number.
return number;
}
};
int main(){
Dice d1,d2;
cout << "d1: " << d1.get_number() << endl;
cout << "d2: " << d2.get_number() << endl;
cout << "After rolling d1: " << d1.roll() << endl;
cout << "After rolling d2: " << d2.roll() << endl;
cout << "The sum of the numbers rolled by the dice is: "
<< d1. get_number() + d2. get_number() << endl;
cout << "After rolling again, the sum of the numbers rolled is: "
<< d1.roll() + d2.roll() << endl;
system("PAUSE");
return 0;
}
22
23. Destructor
You might guess that another function is called automatically
when an object is destroyed.
This is indeed the case. Such a function is called a destructor.
A destructor also has the same name as the class name
but is preceded by a tilde (~) sign:
Like constructors, destructors do not have a return value.
They also take no arguments.
There cannot be more than one destructor in a class.
The most common use of destructors is to de-allocate memory that was
allocated for the object by the constructor.
23
24. Example 6: Destructor A House Example (1/2)
#include <iostream>
using namespace std;
class House{
private: double area; // area in square feet
public:
House() : area(1000) // a zero argument const.
{ cout << "House Created n"; }
House(double a) : area(a) // a 1 argument const.
{ cout << "House Created 1 n"; }
~House() // A Destructor
{ cout<< "House has been destroyed n"; }
double return_area()
{ return area; }
};
int main(){
House H1 , H2(600.0);
cout << "Area of "
<< "House H1 is = " << H1.return_area() << endl
<< "House H2 is = " << H2.return_area() << endl;
system("PAUSE"); return 0; }
24
25. Example 7: Destructor A House Example (1/2)
// A Constructor Example
#include <iostream>
using namespace std;
class House{
private: double area; // Area in square feet
public:
House() : area(1000) // A zero (no) argument constructor
{ cout << "House Created n"; }
~House() // A Destructor
{ cout << "House has been destroyed n"; }
};
void Create_House(){
House aHouse;
cout << "End of function" << endl;
}
int main(){
Create_House();
Create_House();
system("PAUSE"); return 0;
}
25
26. Example 8: Destructor A Student Example (1/3)
#include <iostream>
#include <cstring> // for calling strlen() function
using namespace std;
class Student {
public:
char* name; // A pointer to store address of a string
int length; // to store length of a String
Student() : length(100) { // Make a zero (no) argument constructor and set length = 100
name = new char[length + 1]; // request 101 bytes memory to OS
cout << "No Argument Constructor was called" << endl;
}
Student(const char* src) {// Make a one argument constructor
length = strlen(src) ; // find length of src string
cout << "Requesting "<< length+1 <<" bytes more Memory to OS" << endl;
name = new char[length+1]; // assign memory to name pointer one extra byte is for NULL
strcpy_s(name, length+1, src); // copy string from src to name
} // alternatively you can also use strcpy(name, src); 26
27. Example 8: Destructor A String Example (2/3)
~Student() { /* A destructor */
cout << "Object is Destroyed / Deleted " << endl;
cout << "Therefore returning " << length + 1 <<" bytes Memory to OSn" << endl;
delete[] name; /* return occupied memory to OS */
}
void Show_Name(){
cout << name << endl;
}
void Get_Name(){
cout << "Enter Name:";
cin.get(name, length + 1); fflush(stdin);
}
};
27
28. Example 8: Destructor A String Example (3/3)
int main() {
Student* s1 = new Student("Rashid Farid");
s1->Show_Name();
s1->Get_Name();
s1->Show_Name();
delete s1;
system("PAUSE");
return 0;
}
28
29. Objects as Function Arguments
Next program demonstrates some new aspects of classes, which are:
Constructor Overloading
Defining Member Functions Outside The Class.
Objects as Function Arguments. 29
30. Example 9: Objects As Function Arguments (1/3)
// englcon.cpp constructors, adds objects using member function
#include <iostream>
#include <stdlib.h>
using namespace std;
class Distance // English Distance class
{
private:
int feet; float inches;
public:
Distance() : feet(0), inches(0.0)
{ cout<< "No Arguments Constructor has been Called n" ; }
Distance(int ft, float in) : feet(ft), inches(in)
{ cout<< "Two Arguments Constructor has been Called n" ; }
void getDist(){ // get value of feet and inches from user
cout << "nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
30
31. Example 9: Objects As Function Arguments (2/3)
void showDist(){ // display distance
cout << feet << "'-" << inches << '"';
}
void addDist( Distance, Distance ); // declaration
};
// member function is defined outside the class
void Distance::addDist(Distance d1, Distance d2)
{
inches = d1.inches + d2.inches; // add the inches
feet = 0; // (for possible carry)
if(inches >= 12.0){ // if total exceeds 12.0,
inches -= 12.0; // then decrease inches by 12.0
feet++; // and increase feet by 1
}
feet += d1.feet + d2.feet; // add the feet
}
31
32. Example 9: Objects As Function Arguments (3/3)
int main()
{
Distance dist1, dist3; // Calls no args. constructor
Distance dist2(11, 6.25); // Calls two args. constructor
dist1.getDist(); // get dist1 from user
dist3.addDist(dist1, dist2); // dist3 = dist1 + dist2
// display all lengths
cout << "ndist1 = "; dist1.showDist();
cout << "ndist2 = "; dist2.showDist();
cout << "ndist3 = "; dist3.showDist();
cout << endl;
system("PAUSE");
return 0;
}
32
33. Constructors Overloading
Since there are now two explicit constructors with the same name,
Distance(), we say the constructor is overloaded.
Which of the two constructors is executed when an object is created depends
on how many arguments are used in the definition:
Distance length;
// calls first constructor
Distance width(11, 6.0);
// calls second constructor
33
34. Member Functions Defined Outside the Class
void add_dist( Distance, Distance );
This tells the compiler that this function is a member of the class but that it
will be defined outside the class declaration, someplace else in the listing.
34
35. Objects as Arguments
Since add_dist() is a member function of the Distance class, it can access the
private data in any object of class Distance supplied to it as an argument,
using names like dist1.inches and dist2.feet.
In the following statement dist3.add_dist(dist1, dist2);
add_dist() can access dist3, the object for which it was called, it can also
access dist1 and dist2, because they are supplied as arguments.
When the variables feet and inches are referred to within this function, they
refer to dist3.feet and dist3.inches.
Notice that the result is not returned by the function. The return type of
add_dist() is void.
35
36. Objects as Arguments
The result is stored automatically in the dist3 object.
To summarize, every call to a member function is associated with a particular
object (unless it’s a static function; we’ll get to that later).
Using the member names alone (feet and inches), the function has direct
access to all the members, whether private or public, of that object.
member functions also have indirect access, using the object name and the
member name, connected with the dot operator (dist1.inches or dist2.feet) to
other objects of the same class that are passed as arguments.
36
38. The Default Copy Constructor
We’ve seen two ways to initialize objects.
A no-argument constructor can initialize data members to constant values
A multi-argument constructor can initialize data members to values passed
as arguments.
You can also initialize one object with another object of the same type.
Surprisingly, you don’t need to create a special constructor for this; one is
already built into all classes.
It’s called the default copy constructor. It’s a one argument constructor whose
argument is an object of the same class as the constructor. The next program
shows how this constructor is used.
38
39. Example 10: The Default Copy Constructor (1/2)
// ecopycon.cpp initialize objects using default copy constr.
#include <iostream>
#include <stdlib.h>
using namespace std;
class Distance
{ // English Distance class
private:
int feet; float inches;
public:
Distance() : feet(0), inches(0.0) // constructor (no args)
{ cout<< "No Arguments Constructor has been Called n" ; }
Distance(int ft, float in) : feet(ft), inches(in)
{ cout<< "Two Arguments Constructor has been Called n" ; }
void getdist(){ // get value of feet and inches from user
cout << "nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
39
41. Example 11: Returning Objects from Functions (1/3)
// englret.cpp function returns value of type Distance
#include <iostream>
#include <stdlib.h>
using namespace std;
class Distance{ // English Distance class
private:
int feet; float inches;
public:
Distance() : feet(0), inches(0.0) // constructor (no args)
{ cout<< "No Arguments Constructor has been Called n" ; }
// constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
{ cout<< "Two Arguments Constructor has been Called n" ; }
void getdist(){ // get value of feet and inches from user
cout << "Enter feet : "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
41
42. Example 11: Returning Objects from Functions (2/3)
void showdist() // display feet'-inches"
{ cout << feet << "'-" << inches << '"'; }
Distance add_dist(Distance); // function declaration
};
// add this distance to d2 and return the sum using temp object
Distance Distance::add_dist(Distance d2){ // function definition
Distance temp; // temporary objet
temp.inches = inches + d2.inches; // add the inches
if(temp.inches >= 12.0){ // if total exceeds 12.0,
temp.inches -= 12.0; // then decrease inches by 12.0 and
temp.feet = 1; // increase feet by 1
}
temp.feet += feet + d2.feet; // add the feet
return temp; // return value of temporary objet
}
42
43. Example 11: Returning Objects from Functions (3/3)
int main()
{
Distance dist1, dist3; // define two lengths
Distance dist2(11, 6.25); // define, initialize dist2
dist1.getdist(); // get dist1 from user
dist3 = dist1.add_dist(dist2); // dist3 = dist1 + dist2
cout << "ndist1 = " ; dist1.showdist(); // display all lengths
cout << "ndist2 = " ; dist2.showdist();
cout << "ndist3 = " ; dist3.showdist();
cout << endl;
system("PAUSE");
return 0;
}
43
44. Returning Objects from Functions
To execute the statement dist3 = dist1.add_dist(dist2);
A temporary object of class Distance is created to store the sum.
The sum is calculated by adding two distances.
The first is the object dist1, of which add_dist() is a member. Its member
data is accessed in the function as feet and inches.
The second is the object passed as an argument, dist2. Its member data is
accessed as d2.feet and d2.inches.
The result is stored in temp and accessed as temp.feet and temp.inches.
The temp object is then returned by the function using the statement return
temp;
The statement in main() assigns it to dist3.
44
45. Returning Objects from Functions
Notice that dist1 is not modified; it simply supplies data to add_dist().
Figure on next slide shows how this looks.
In the topic, “Operator Overloading”, we’ll see how to use the arithmetic +
operator to achieve the even more natural expression like dist3 = dist1 + dist2;
45
47. Structures and Classes
In fact, you can use structures in almost exactly the same way that you use
classes. The only formal difference between class and struct is that in a class
the members are private by default, while in a structure they are public by
default. You can just as well write
class foo
{
int data1;
public:
void func();
}; //and the data1 will still be private.
47
48. Structures and Classes
If you want to use a structure to accomplish the same thing as this class, you
can dispense with the keyword public, provided you put the public members
before the private ones
struct foo{
void func();
private:
int data1;
}; // since public is the default.
However, in most situations programmers don’t use a struct this way. They use
structures to group only data, and classes to group both data and functions.
48
49. Classes, Objects and Memory
You might have the impression that each object
created from a class contains separate copies of
that class’s data and member functions.
It’s true that each object has its own separate data
items
But all the objects in a given class use the same
member functions.
The member functions are created and placed in
memory only once—when they are defined in the
class definition.
Since the functions for each object are identical.
The data items, however, will hold different values.
49
data1
data2
Object 3
data1
data2
Object 3
data1
data2
Object 3
Function1()
Function2()
50. static Class Data
If a data item in a class is declared as static, only one such item is created for
the entire class, no matter how many objects there are.
A static data item is useful when all objects of the same class must share a
common item of information.
A member variable defined as static has characteristics similar to a normal
static variable: It is visible only within the class, but its lifetime is the entire
program. It continues to exist even if there are no objects of the class.
A normal static variable is used to retain information between calls to a
function, static class member data is used to share information among the
objects of a class.
50
51. static Data in a Class
Why would you want to use static member data? As an example, suppose an
object needed to know how many other objects of its class were in the
program.
In a road-racing game, for example, a race car might want to know how many
other cars are still in the race.
In this case a static variable Total_Cars could be included as a member of the
class. All the objects would have access to this variable. It would be the same
variable for all of them; they would all see the same number of Total_Cars.
51
52. Example 12: static Data in a Class (1/2)
// statdata.cpp demonstrates a simple static data member
#include <iostream>
#include <stdlib.h>
using namespace std;
class Car{
private:
static int Total_Cars; // only one data item for all objects
// note: "declaration" only!
public:
Car() // increments count when object created
{ Total_Cars++; }
int How_Many() // returns count
{ return Total_Cars; }
~Car()
{ Total_Cars--; } // decrement count when an object is destroyed
};
int Car::Total_Cars = 0; // initialization of count
52
53. Example 12: static Data in a Class (2/2)
int main()
{
Car Toyota, Honda, Suzuki; // create three objects
cout << Toyota.How_Many() << " Cars are in Race" << endl;
cout << Honda.How_Many() << " Cars are in Race" << endl;
// each object sees the same data
cout << Suzuki.How_Many() << " Cars are in Race" << endl;
Car *Pajero = new Car; // create a nameless objet and store
// its starting address in a pointer p
cout << Suzuki.How_Many() << " Cars are in Race" << endl;
cout << Pajero->How_Many() << " Cars are in Race" << endl;
delete Pajero;
cout << Honda.How_Many() << " Cars are in Race" << endl;
system("PAUSE");
return 0;
}
53
54. static Members Data
Ordinary variables are usually declared (the compiler is told about their name
and type) and defined (the compiler sets aside memory to hold the variable) in
the same statement. e.g. int a;
Static member data, on the other hand, requires two separate statements.
The variable’s declaration appears in the class definition,
but the variable is actually defined outside the class, in much the same way
as a global variable.
If static member data were defined inside the class, it would violate the idea
that a class definition is only a blueprint and does not set aside any memory.
54
55. Example 13: const Member Function
//constfu.cpp demonstrates const member functions
class aClass
{
private:
int alpha;
public:
void nonFunc() // non-const member function
{
alpha = 99; // OK
}
void conFunc() const // const member function
{
alpha = 99; // ERROR: can’t modify a member
}
};
55
A const member function guarantees that it will never modify any of its class’s
member data.
56. Example 14: Distance Class and Use of const (1/3)
// const member functions & const arguments to member functions
#include <iostream>
using namespace std;
class Distance // English Distance class
{
private:
int feet; float inches; // attributes
public:
Distance() : feet(0), inches(0.0)
{ } // constructor (no args)
Distance(int ft, float in) : feet(ft), inches(in)
{ } // constructor (two args)
void getdist(){ // get value of feet and inches from user
cout << "nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
56
57. Example 14: Distance Class and Use of const (2/3)
void showdist() const // display distance
{ cout << feet << "'-" << inches << '"'; }
Distance add_dist(const Distance&) const; // add two objects
};
//add this distance to d2, return the sum
Distance Distance::add_dist(const Distance& d2) const
{
Distance temp; // temporary variable
// feet = 0; // ERROR: can’t modify this
// d2.feet = 0; // ERROR: can’t modify d2
temp.inches = inches + d2.inches; // add the inches
if(temp.inches >= 12.0) // if total exceeds 12.0,
{ temp.inches -= 12.0; // then decrease inches by 12.0
temp.feet = 1; // and increase feet by 1
}
temp.feet += feet + d2.feet; // add the feet
return temp; // return temp object
}
57
58. Example 14: Distance Class and Use of const (3/3)
int main()
{
Distance dist1, dist3; // define two lengths
Distance dist2(11, 6.25); // define, initialize dist2
dist1.getdist(); // get dist1 from user
dist3 = dist1.add_dist(dist2); // dist3 = dist1 + dist2
//display all lengths
cout << "ndist1 = "; dist1.showdist();
cout << "ndist2 = "; dist2.showdist();
cout << "ndist3 = "; dist3.showdist();
cout << endl;
system("PAUSE");
return 0;
}
58
59. const Member Function Arguments
If an argument is passed to an ordinary function by reference, and you don’t
want the function to modify it, the argument should be made const in the
function declaration (and definition). This is true of member functions as well.
Distance Distance::add_dist(const Distance& d2) const{
In above line, argument to add_dist() is passed by reference, and we want to
make sure that won’t modify this variable, which is dist2 in main().
Therefore we make the argument d2 to add_dist() const in both declaration
and definition.
59
60. const Objects
In several example programs, we’ve seen that we can apply const to variables
of basic types such as int to keep them from being modified.
In a similar way, we can apply const to objects of classes. When an object is
declared as const, you can’t modify it.
It follows that you can use only const member functions with it, because
they’re the only ones that guarantee not to modify it. e.g. A football field (for
American-style football) is exactly 300 feet long. If we were to use the length
of a football field in a program, it would make sense to make it const, because
changing it would represent the end of the world for football fans.
60
61. Example 15: const Objects (1/2)
// constObj.cpp constant Distance objects
#include <iostream>
using namespace std;
class Distance // English Distance class
{
private:
int feet;
float inches;
public:
Distance(int ft, float in) : feet(ft), inches(in)
{ } // 2-arg constructor
void getdist() // user input; non-const function
{
cout << "nEnter feet:" ; cin >> feet;
cout << "Enter inches:" ; cin >> inches;
}
61